import $service from '../../../service.js';

const app = getApp()
var log_id; //问诊id
var log_type; //问诊类型
var isShow = true; //用户是否在线
var hospitalizationList = {}; //住院列表
var inquiry_patient_id; //患者id
var backhome = 1 //医生是否退出问诊 1 未 2 是
var page = 0;
var thenS_;
var getMap; //获取用药map
var druglistStorage_z = []; //已选中药处方 列表
var druglistStorage_x = []; //已选西药处方 列表
var template_prescriptionList = {} //保存模板list
var dataId = ''; //检验检查
var checklistId; // 检验项目意见单 id
var checklistListAll; //检验检查
var StorageJosn; //生成处方
var prescriptionListlength = []; //已生成处方list
var template_id; //诊断id
var numText; //添加文字用 诊断
var bcmb_diagnosis_id;
// 西药开处方计算用Obj
var selectionunitNum = 0;
var medicineObj = null;
var tapMap_type;
var pageclose = true; //true //显示弹窗 false不显示弹窗
var rz_addTriageNote = true; //false 为分诊

let imId = ''; // 患者imID
let doctorIM = ''; // 医生imID
let logId = ''; // 问诊id
let inquiryPatientId = '';
let doctorId;
let _this;
let oosParams = {};
let chat = null;
let isNetWork = true
let isEnd = true
let patientName = ''
let lianjiangInquiryListStartDate = ''
let lianjiangInquiryListEndDate = ''
let clinicPage = 1
let inqiuryLoading = true
let isImgShow = false
let detailsEntrust = ''

Page({
    txTic: null,
    webrtcroomComponent: null,
    /**
     * 页面的初始数据
     */
    data: {
        TRTCTYPE: $service.TRTCTYPE,
        queryLogHis: [],
        searchKeywords: "",
        loginMiniQrcodeurl: '',
        autoPreList: [],
        deliveryMode: 1,
        payWay: 1,
        isFirstInquiry: 0,
        hisModal: false,
        isShowPrescription_taking: true,
        hospitalType: $service.hospitalType,
        hisType: $service.isHis,
        msgList: [],
        tencentConfig: {},
        userIDImg: '',
        selToID: "", //对方聊天账号
        selToIDImg: '',
        scrollTop: 0,
        increase: false, //图片添加区域隐藏
        aniStyle: true, //动画效果
        message: "",
        previewImgList: [],
        imUserInfo: {}, //im用户信息
        imSelToUserInfo: {}, //im对方用户信息
        isJoinClassroom: false, // 是否已经在课堂中
        template: '1v1bigsmall', //视频用
        smallViewLeft: 'calc(100vw - 20vw - 1vw)', //视频用
        smallViewTop: 'calc(1vw)', //视频用
        smallViewWidth: '20vw', //视频用
        smallViewHeight: '26vw',
        enableCamera: true, // 是否启用摄像头
        loadingImg: '',
        playerBackgroundImg: '',
        boardShowFullScreen: true, // 是否全屏显示白板
        islistshow: false, //常用语弹窗
        rtsytViewZt: true, //人体示意图显示隐藏
        log_type: 2,
        inputHeight: 0, //监听input弹起高度
        measuredDataList: [], //测量数据list
        measuredDataMap: {}, //测量数据map
        num: 0, //测量数据
        loadingText: '',
        loadingType: true,
        timeList: [], //图片列表
        wzlslist: [], //问诊历史list
        inquiryMap: {}, //诊断
        prescriptionList: [], //已开处方列表
        drug_type: 1, //处方类型 1中药 2 西药
        tabactive: '', //处方诊断 //0过敏史 1 主诉 2现病史 3既往史 4诊断
        type: 0,
        openPageBox: 0, //打开弹窗  // 1查询病历 2检验检查 3健康指导意见单 4查询图片 5人体示意 6住院建议书 7问诊规范 8结束问诊 9开处方 10修改患者资料 11分诊  12常用语 13 测量数据 14查询历史问诊 15开处方-选择开药 16 开处方-生成处方 17检验检查-心电图 18检验检查-申请单  19健康指导-健康指导意见单详情填写 20填写诊断信息、主诉、过敏史等 21药品信息 22 保存模板 23处方详情 24 检验检查详情 25健康指导详情 26住院建议详情
        openPageBox_up: 0, //上级的 openPageBox
        tapactive: 1, //处方选项卡
        drugList: [], //处方 目录、分类
        drugList2: [], //处方 个人用药
        drugList3: [], //处方 公共模板 、个人模板
        drugList4: [], //处方 历史处方
        drug_name: '', //处方  请输入药品名称或首字母
        class_name: '', // 处方 分类选择框
        drugClassList: [], //处方 药品分类列表
        isshow: false, //处方 选择分类弹窗显示隐藏
        class_id: '', //处方 分类id
        isdetalis: false, //处方 查看详情
        diagnosisMap: [], //处方 模板详情
        prescriptionMap: {}, //处方 模板详情列表
        drugMap: {}, //开药详情
        consumptionlist: [], //用量单位list
        useUnit: "", //默认用量单位
        list: [], //用法list
        list2: [], //频次list
        list3: [], //嘱托list
        details_usage: '', //用法
        details_consumption: '', //用量
        details_consumption_util: '', //用量单位
        details_frequency: '', ///频率,
        details_frequency_str: '',
        details_frequency_str2: '',
        details_day: '', //天数
        details_num: '', //盒数
        storeName: '',
        storeId: '', //药店ID
        shopId: '', //搜索时药店ID
        storeData: {}, //搜索时药店信息
        islist: false, //弹窗显示隐藏
        islist2: false, //弹窗显示隐藏
        islist3: false, //弹窗显示隐藏
        isconsumptionlist: false, //弹窗显示隐藏
        drug_packaging_unit: '', //盒数单位
        getdruglistStoragelist: [], //已选处方
        sccfisshow: 0, //开药显示
        prescription_price: 0, //处方金额
        prescription_taking: '', //服用方法
        prescription_requirements: '', //服用要求
        prescription_num: '', //付数
        prescription_isdetalis: false, //生成中药弹窗
        frequency_num: 0,
        frequency_day_num: 0,
        selectionunit: 0,
        drug_packaging_num: 1,
        isClassList: 1, //检验检查
        checklistClassList: [], // 检验检查 大分类列表
        nextClassList: [], //检验检查 二分类列表
        checklistList: [], //检验检查 三分类列表
        checkThreeList: [], //检验检查 四分类列表
        isThree: false, // 是否有三级菜单
        dataId: '', //一级
        dataId2: '', //二级
        opinionList: [], //已开检验检查  检验项目意见单
        opinionList2: [], //已开检验检查  检查项目意见单
        opinionList3: [], //已开检验检查 已开检验检查申请单
        lof_proposal: '', //建议检查 医生建议
        checklist_objMap: '', //验检查申请单内容
        checklist_name: '', //检验检查项目名字
        checklist_last_code: '', //上次单号
        checklist_abstract: '', //摘要
        checklist_sbp: '', //收缩压
        checklist_dbp: '', //舒张压
        lof_diagnosis: '', //临床诊断
        is_digitalization: 0, //是否使用过洋地黄  0否 1是
        checklist_digitalization_num: '', //使用洋地黄用量
        checklist_digitalization_start: '', //使用洋地黄开始时间
        checklist_digitalization_end: '', //使用洋地黄结束时间
        is_other_drugs: 0, //是否使用有关药物    0否 1是
        checklist_other_drugs_name: '', //有关药物名称
        checklist_other_drugs_start: '', //有关药物开始时间
        checklist_other_drugs_end: '', //有关药物结束时间
        checklist_other_drugs_num: '', //有关药物用量
        checklist_inspection_result: '', //有关检验结果
        bz: '', //备注
        beforeYear: '', //使用洋地黄开始时间 年
        beforeMon: '', //使用洋地黄开始时间 月
        beforeDay: '', //使用洋地黄开始时间 日
        beforeYear2: '', //有关药物开始时间 年
        beforeMon2: '', //有关药物开始时间 月
        beforeDay2: '', //有关药物开始时间 日
        newYear: '', //使用洋地黄结束时间 年
        newMon: '', //使用洋地黄结束时间 月
        newDay: '', //使用洋地黄结束时间 日
        newYear2: '', //有关药物结束时间 年
        newMon2: '', //有关药物结束时间 月
        newDay2: '', //有关药物结束时间 日
        jyjcXdbisshow: false, //心电图
        jyjcXdb_isClassList: 1,
        jyjcXdb_nextClassList: [], //一级列表
        jyjcXdb_checklistList: [], //二级列表
        jyjcXdb_opinionList: [], //已选中检验项目
        jyjcXdb_dataId2: '',
        jyjcXdb_checklist_abstract: '', //摘要
        jyjcXdb_checklist_inspection_result: '', //有关检验结果
        jyjcXdb_bz: '', //备注
        health_active: true, //健康指导选项卡
        guidance_name: '', //健康指导内容搜索
        carouselActivityList: [], //健康指导列表
        health_isdetalis: false, //弹窗
        guidance_nameText: '', //弹窗内容
        jkzdxqtx_active: true, //填写健康指导意见单
        hiddenName: true, //下拉框内容
        selected: 1, //填写健康指导意见单选项卡
        hiddenpop: true, //弹窗
        showModal: false,
        guidance_content: '', //输入内容
        doctorMap: {}, //医生资料
        guidanceList: [], //指导list
        jkzdxqtx_isdetalis: false, //弹窗
        jkzdxqtx_guidance_nameText: '', //弹窗内容
        zyjys_bz: '', //健康指导备注
        wzgf_active: 1, //问诊规范
        wzgf_list: [], //问诊规范 问诊流程
        wzgf_list2: [], //药品规范
        wzgf_list3: [], //诊断规范
        wzgf_queryName: '', //问诊话术搜素
        wzgf_isdetalis: false, //问诊规范 弹窗
        wzgf_drugMap: {}, //问诊规范弹窗内容
        incompatibilityList: [], //药品冲突list
        tabactive: 1, //填写诊断。主诉 。过敏史 选项卡
        templateList: [], //list
        mould: 0, //模板选项卡
        text: '', //显示内容
        txdiagnosis_iinquiry_patient_allergy_details: '', //过敏史
        txdiagnosis_log_main_suit: '', //主诉
        txdiagnosis_log_present_illness: '', //现病史
        txdiagnosis_log_history_present_illness: '', //既往史
        txdiagnosis_lof_diagnosis: '', //诊断
        txdiagnosis_isdetalis: false,
        txdiagnosis_isdetalistype: 1,
        template_type: '', //模板类型
        template_name: '', //模板名称
        template_details: '', //模板详情
        template_list: ['主诉', '现病史', '既往史'],
        txdiagnosis_islist2: false,
        txdiagnosis_isdiagnosis: false, //自定义诊断弹窗
        isdiagnosisText: '', //自定义诊断
        txdiagnosis_name: '', //搜索
        diagnosis_list: [], //已开诊断列表
        activeIndex: '', //诊断列表选中下标
        inputtext: '', //补充的值
        ypxx_drugMap: {}, //药品信息
        xghzzl_isshow: false, //职业选择窗口
        tsqk_isshow: false, //特殊情况窗口
        starttime: '', //日期开始时间
        endtime: '', //结束时间
        xghzzl_list: [], // 职业列表
        tsqk_list: [{
          text: '无',
          value: ''
        },{
          text: '备孕',
          value: '备孕'
        },{
          text: '怀孕',
          value: '怀孕'
        },{
          text: '哺乳期',
          value: '哺乳期'
        }], // 特殊情况列表
        inquiryMap2: {
          isMarried: 0,
          addressCity: ''
        }, //患者资料信息
        bcmb_icd_id: '', //保存模板分类id
        bcmb_icd_name: '', //分类名称
        bcmb_bz: '', //备注
        bcmb_prescription_price: '0', //处方价格
        bcmb_prescription_name: '', //处方名称
        bcmb_prescription_taking: '', //服用方法
        bcmb_prescription_requirements: '', //服用要求
        bcmb_prescription_num: '', //付数
        bcmb_list: [],
        bcmb_list2: [],
        bcmb_diagnosisList: [],
        bcmb_queryName: '',
        bcmb_isullist: false,
        bcmb_type: 0,
        prescription_imgurl: '', //处方详情 图片
        checklist_imgurl: '', //检验检查详情 图片
        guidance_imgurl: '', //健康指导详情 图片
        application_imgurl: '', //申请单详情 图片
        hospitalization_imgurl: '', //住院建议详情 图片
        bg_view_show: false, //输入框 解决等级高问题
        isinputShowed: false, //输入框 解决等级高问题
        inputShowed: false, //输入框 解决等级高问题
        isinputShowed2: false, //输入框 解决等级高问题
        inputShowed2: false, //输入框 解决等级高问题
        isinputShowed3: false, //输入框 解决等级高问题
        inputShowed3: false, //输入框 解决等级高问题
        isinputShowed4: false, //输入框 解决等级高问题
        inputShowed4: false, //输入框 解决等级高问题
        isinputShowed5: false, //输入框 解决等级高问题
        inputShowed5: false, //输入框 解决等级高问题
        isinputShowed6: false, //输入框 解决等级高问题
        inputShowed6: false, //输入框 解决等级高问题
        isinputShowed7: false, //输入框 解决等级高问题
        inputShowed7: false, //输入框 解决等级高问题
        isdatalook: false, //测量数据
        isimglook: false, //查询图片
        fzdoctorList: [], //分诊 医生列表
        fzisshow: false, //弹窗
        fzactivenum: -1,
        fzdepartmentList: [],
        fzdepartment_id: '',
        fzdoctor_name: '',
        syncFlag: true, //同步处方按钮显示
        prescription_id: "",
        noPrescriptionList: [], //未开方原因列表
        reasonsName: '其他', //未开发原因
        isWithdrawShow: false, // 是否展示撤回弹窗
        toView: '',
        messageHeight: '', // 底部操作栏高度
        myIM: '', // 自己的IMid
        friendIM: '', // 对方的IMid
        userName: '', // 自己的名称
        doctorStoreList: [], //药店列表
        valueIndex: 0, //中药分类选择index
        wmValueIndex: 0, //西药分类选择index
        storeIndex: 0, //药店来源列表index
        wmstoreIndex: 0, //西药药店来源列表index
        scrollTop: 0, //滚动条高度
        paymentMethodNum: 0, //问诊付费类型
        paymentMethodList: ["自费缴费", "医保缴费"],
        isPickerShow: false, //分类弹窗picker是否弹出,
        medListIndex: 0,
        diseaseArray: [], //病种列表(医保)
        diseaseIndex: 0, //index
        diseaseMessage: "", //选中的病种信息
        dosage:"",  //药品剂量(医保)
        isAuto: 0, // 是否是自主开方
        clinicSeq: '',
        logId: '',
        isEsgin: $service.isEsgin
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (e) {
        log_id = e.log_id
        doctorId = JSON.parse($service.getStore('userInfo')).id
        if (e.isAuto == 0) {
          wx.hideHomeButton()
          this.data.openPageBox = 0
          imId = e.imId;
          logId = e.logId;
          doctorIM = e.doctorIM;
          inquiryPatientId = e.inquiryPatientId;
          patientName = e.patientName
          log_type = e.log_type
          this.getBeforeDate(14);
          var d = new Date();
          var year = d.getFullYear();
          var mon = d.getMonth() + 1;
          mon = mon < 10 ? ('0' + mon) : mon;
          var day = d.getDate();
          day = day < 10 ? ('0' + day) : day;
          this.setData({
              beforeYear2: year,
              beforeMon2: mon,
              beforeDay2: day,
              newYear: year,
              newMon: mon,
              newDay: day,
              newYear2: year,
              newMon2: mon,
              newDay2: day,
              loadingImg: '',
              playerBackgroundImg: '',
              boardShowFullScreen: true, // 是否全屏显示白板
              islistshow: false, //常用语弹窗
              rtsytViewZt: true //人体示意图显示隐藏
          })
          this.publicUtil_getInquiryLogDetails()
          this.ossPolicy()
          this.getMessageheight() // 获取聊天历史
          this.watchNetWork() //监听网络
        } else {
          logId = e.logId;
          inquiryPatientId = e.inquiryPatientId;
          if (logId) {
            this.publicUtil_getInquiryLogDetails()
          }
          this.data.openPageBox = 9
        }
        wx.setNavigationBarTitle({
            title: e.isAuto == 1 ? '自主开方' : e.patientName
        })
        this.setData({
            logId: e.logId,
            patientName: e.patientName,
            openPageBox: this.data.openPageBox,
            isAuto: e.isAuto,
            friendIM: e.imId,
            myIM: e.doctorIM,
            log_type: e.log_type,
            userName: JSON.parse($service.getStore('userInfo')).trueName
        })
        lianjiangInquiryListStartDate = ''
        lianjiangInquiryListEndDate = ''
        clinicPage = 1
        inqiuryLoading = true
    },
    onShow() {
        wx.setKeepScreenOn({
          keepScreenOn: true
        })
        pageclose = true;
        backhome = 1
        thenS_ = this.data;
        rz_addTriageNote = true; //false 为分诊
        if (this.data.isAuto == 0) { // 非自主开方
          this.initWebSocket();
          if (log_type == 1) {
            this.webrtcroomComponent = this.selectComponent('#webrtcroom');
            this.startRTC();
          }
          chat = this.selectComponent('#chat')
          this.publicUtil_getInquiryLogDetails()
        } else { // 自主开方

        }
    },
    onReady() {
        this.bottom();
    },
    // 页面卸载
    onUnload() {
        if (this.data.isAuto == 0) {
          app.webSocket.closeWebSocket()
          var this_ = this
          pageclose = false
          if (log_type == 1) {
              this.webrtcroomComponent.exitRoom();
          }
        } 
    },
    // 初始化socket
    initWebSocket() {
        if (!app.webSocket.init) {
            app.webSocket.initWebSocket({
                url: $service.wsUrl
            });
            // if (!isNetWork) {
                app.webSocket.onSocketOpened(() => {
                    let params = {
                        "logId": logId, //问诊id
                        "doctorIM": doctorIM, //医生im
                        "doctorName": this.data.userName, //医生姓名
                        "patientIM": imId, //患者im
                        "userId": inquiryPatientId, //用户id
                        "packageType": 26,
                    }
                    app.webSocket.sendWebSocketMsg({
                        data: params,
                        success: () => {
                            isNetWork = !isNetWork
                        }
                    })
                })
            // }
        }
        this.sendLogin();
        app.webSocket.onReceivedMsg(res => { // 监听websocket事件
            console.log(res)
            if (res.packageType === 16) { // 分诊成功
                rz_addTriageNote = false;
                wx.showToast({
                    "title": '分诊成功',
                    "icon": "none",
                    duration: 4000
                });
                setTimeout(function () {
                    wx.reLaunch({
                        url: '/pages/doctor_side/index/index'
                    })
                }, 1500);
            } else if (res.packageType === 3) { // 接收自己发送的信息
                chat.myMessage(res);
            } else if (res.packageType === 4) { // 接收对方发送的信息
              if (res.userId == imId || (res.msgUserName == this.data.patientName && res.userId == 0) || res.msgType == 5) {
                    if (res.msgType == 7) {
                        chat.getChatRecordList('reset')
                    } else if (res.msgType == 8) {
                        console.log(res);
                        chat.isReadMessage()
                    } else {
                        this.isRead()
                        chat.tagetMessage(res);
                    }
                }
            }
            if (log_type == 1 || log_type == 2) {
                if (res.packageType === 14) { // 接收问诊结束信号
                    if (imId == res.imId) {
                        $service.showToast('用户已结束问诊')
                        thenS_.openPageBox = 27;
                        this.noPrescriptionList();
                        this.setData({
                            openPageBox: thenS_.openPageBox,
                        })
                    }
                } else if (res.packageType === 9) { // 接收对方离线信号
                    wx.showModal({
                        title: '提示',
                        content: '用户已掉线',
                        showCancel: true,
                        confirmText: "确定",
                        success: (res) => {
                            if (res.confirm) {
                                thenS_.openPageBox = 27;
                                this.noPrescriptionList();
                                this.setData({
                                    openPageBox: thenS_.openPageBox,
                                })
                            } else {
                                this.setData({
                                    openPageBox: 0
                                })
                            }
                        },
                    })
                }
            }
        })
        console.log(isImgShow)
        if (!isImgShow) {
          this.isRead() //调用一次39确保已读
        }
        isImgShow = false
    },

    // 向对方发送上线信息
    sendLogin() {
        app.webSocket.sendWebSocketMsg({ // 告诉对方已上线
            data: {
                "userIm": this.data.myIM, //发送方im
                "friendIm": this.data.friendIM,
                "packageType": 38,
            },
        })
    },
    //收到对方的消息，确认已读
    isRead() {
        // 传递一个39事件保证已读
        let dataMsg = {
            "userId": imId, //发送方id
            "friendId": doctorIM, //接收方id
            "packageType": 39,
        }
        app.webSocket.sendWebSocketMsg({
            data: dataMsg,
            success: (res) => {
                console.log(res);
            }
        })
    },
    //问诊详情
    publicUtil_getInquiryLogDetails: function () {
        let _this = this;
        app.http.getAllInfo({
            id: logId
        }).then(res => {
            let data = $service.deepClone(res.data);
            let arr = []
            if (data.diagnosisArray) {
                data.diagnosisArray.forEach(item => {
                    arr.push(item.diagnosis)
                })
                data.diagnosis = arr.join()
            }
            prescriptionListlength = data.prescriptionList
            hospitalizationList = data.hospitalizationDetailResp
            if ((Number(data.paymentMethod) - 1) == 1) {
                this.setData({
                    isPickerShow: true
                })
            }

            //判断paymentMethod为null
            let ispaymentMethod = 0;
        
            if(data.paymentMethod == null||data.paymentMethod==1){
                ispaymentMethod = 0;
            }
            else{
                ispaymentMethod = 1;
            }   

            _this.setData({
                diseaseMessage:{"diseaseName":data.diseaseName,"diseaseCode":data.diseaseCode},
                inquiryMap: data,
                inquiryMap2: data,
                selToIDImg: data.patientImg,
                userIDImg: JSON.parse($service.getStore('doctorInfo')).doctorHeadImg,
                opinionList2: data.inspectionOpinionList,
                opinionList3: data.formListResult,
                prescriptionList: data.prescriptionList,
                guidanceList: data.inquiryLogHealthGuidanceList,
                doctorMap: JSON.parse($service.getStore('doctorInfo')),
                paymentMethodNum: ispaymentMethod,
            })
            // this.getDoctorStoreList() //获取药店列表
            console.log('结束没有')
            if (this.data.isAuto == 0 && (res.data.state != 0)) {
              console.log('结束了')
              $service.showToast('用户已结束问诊')
              thenS_.openPageBox = 27;
              this.noPrescriptionList();
              this.setData({
                  openPageBox: thenS_.openPageBox,
              })
            }
        }).catch(err => {
            console.log(err)
            $service.showToast(err.msg)
        })
    },
    //回调
    //事件处理函数 
    // 发送聊天消息
    send: function () {
        var that = this;
        if (this.data.message == "") {
            wx.showToast({
                title: '消息不能为空哦~',
                icon: "none",
                duration: 2000
            })
        } else {
            that.bottom()
            let msgData = {
                "msgText": this.data.message, // 信息体
                "friendId": imId, // 接收方的用户imID
                "msgUserName": this.data.inquiryMap.doctorName,
                "msgType": 0, // 消息类型；0文字消息、1固定表情 3 图片url
                "inquiryLogId": logId,
                "msgDate": $service.getDate(), // 发送时间
                "packageType": 3 // 信息包类型
            }
            app.webSocket.sendWebSocketMsg({
                data: msgData,
                success: () => {
                    this.setData({
                        message: "",
                        increase: false
                    })
                },
                fail: () => {
                    $service.showToast('发送失败')
                }
            })
        }
    },

    //监听input值的改变
    bindChange(res) {
        this.setData({
            message: res.detail.value
        })
    },
    cleanInput() {
        //button会自动清空，所以不能再次清空而是应该给他设置目前的input值
        this.setData({
            message: this.data.message
        })
    },
    increase() {
        this.data.increase = !this.data.increase
        this.setData({
            increase: this.data.increase,
            aniStyle: true
        })
    },
    //点击空白隐藏message下选框
    outbtn() {
        this.setData({
            increase: false,
            aniStyle: true,
            isWithdrawShow: false
        })
    },
    //图片预览
    previewImg(e) {
        var that = this
        //必须给对应的wxml的image标签设置data-set=“图片路径”，否则接收不到
        var res = e.target.dataset.src
        var list = this.data.previewImgList //页面的图片集合数组

        //判断res在数组中是否存在，不存在则push到数组中, -1表示res不存在
        if (list.indexOf(res) == -1) {
            this.data.previewImgList.push(res)
        }
        let urls = []
        this.data.previewImgList.forEach(item => {
            urls.push(item.replace(/https/, 'http'))
        })
        wx.previewImage({
            urls: urls // 需要预览的图片http链接列表
        })
    },
    //聊天消息始终显示最底端
    bottom() {
        this.setData({
            toView: 'flag'
        })
    },
    //返回顶部
    getpageScrollTo() {
        wx.pageScrollTo({
            scrollTop: 0
        })
    },
    
   

  


    // 开始RTC
    startRTC() {
        if ($service.getStore('tencentConfigD')) {
          this.setData({
              tencentConfig: $service.getStore('tencentConfigD'), 
              boardShowFullScreen: false
          })
        }
    },
   
    /**
     * 显示信息弹窗
     * @param {*} msg 
     * @param {*} error 
     */
    showToast: function (msg) {
        wx.showToast({
            icon: 'none',
            title: msg
        });
    },

    //获取药店列表
    getDoctorStoreList() {
        if (this.data.paymentMethodNum == 1) {
            this.setData({
                doctorStoreList: [{
                    group_name: '医保平台'
                }]
            })
        } else {
            app.http.getStoreList('').then(res => {
                res.data.unshift({
                    group_name: '全部'
                })
                this.setData({
                    doctorStoreList: res.data
                })
            })
        }
    },
    // 打开弹窗
    openPage(e) { // 1查询病历 2检验检查 3健康指导意见单 4查询图片 5自主开方历史记录 6住院建议书 7问诊规范 8结束问诊 9开处方 10修改患者资料 11分诊  12常用语 13 测量数据 14查询历史问诊 15开处方-选择开药 16 开处方-生成处方 17检验检查-心电图 18检验检查-申请单  19健康指导-健康指导意见单详情填写 20填写诊断信息、主诉、过敏史等 21药品信息 22 保存模板 23处方详情 24 检验检查详情 25健康指导详情 26住院建议详情 32编辑医嘱
        this.setData({
            isWithdrawShow: false
        }) // 隐藏撤回弹窗
        var index = e.currentTarget.dataset.index;
        if (logId) {
          this.publicUtil_getInquiryLogDetails()
        } else if (!logId && (index == 1 || index == 8) && this.data.isAuto == 1) {
          $service.showToast('请先填写就诊人信息')
          return
        }
        if (index == 2) { // 检验检查
            this.setData({
                isClassList: 1, //检验检查
                checklistClassList: [], // 检验检查 大分类列表
                nextClassList: [], //检验检查 二分类列表
                checklistList: [], //检验检查 三分类列表
                dataId: '', //一级
                dataId2: '', //二级
                opinionList: [], //已开检验检查  检验项目意见单
                opinionList2: [], //已开检验检查  检查项目意见单
                opinionList3: [], //已开检验检查 已开检验检查申请单
            })
            this.doctorSide_personal_inquiry_getUtilChecklistClass();
        } else if (index == 3) { // 3健康指导意见单
            this.getHealthGuidanceModelList()
        } else if (index == 4) { //4查询图片
            this.getChatImages(logId)
            this.setData({
                isimglook: false //查询图片
            })
        } else if (index == 9) {
          this.getDiseaseNameList()
        } else if (index == 6) { //住院建议书
            thenS_.openPageBox_up = index;
            thenS_.openPageBox = index;
            if (!hospitalizationList) {
                thenS_.openPageBox = index;
            } else {
                console.log(hospitalizationList)
                thenS_.openPageBox = 26;
                this.getEstablishPdf(logId, 1)
            }
            this.setData({
                openPageBox: thenS_.openPageBox,
                openPageBox_up: thenS_.openPageBox_up
            })
        } else if (index == 7) { //7问诊规范
            page = 1
            this.setData({
                wzgf_active: "1"
            })
            this.doctorSide_personal_inquiry_getSpecification()
        } else if (index == 8) { //结束问诊
            thenS_.openPageBox = 27;
            this.noPrescriptionList();
            this.setData({
                openPageBox: thenS_.openPageBox,
            })
        } else if (index == 10) { //修改患者资料
            this.publicUtil_getUtilTable10()
            this.getDiseaseNameList()
        } else if (index == 11) {
            this.getDepartmentListPc();
            this.getOnlineDoctorList();
        } else if (index == 12) { //常用语
            let params = {
                "current": 1,
                "modelName": "",
                "size": 5
            }
            app.http.getDoctorNormalConsultationList(params).then(res => {
                this.setData({
                    islistshow: !this.data.islistshow,
                    list: res.data.list
                })
            })
        } else if (index == 13) { //测量数据
            page = 1
            this.publicUtil_getPatientMeasuredDataList('now');
            this.publicUtil_getPatientMeasuredDataList('history');
            this.setData({
                isdatalook: false //测量数据
            })
        } else if (index == 14) {
          this.queryInquiryLogPrescriptionHistory()
          this.getpageScrollTo()
          thenS_.openPageBox = 30;
          this.setData({
              openPageBox: thenS_.openPageBox,
          })
        } else if (index == 32) {
          console.log(111)
        }
        if (index != 5 && index != 6 && index != 8 && index != 14 && index != 12) {
            thenS_.openPageBox_up = thenS_.openPageBox;
            this.setData({
                openPageBox: index,
                openPageBox_up: thenS_.openPageBox_up
            })
            this.getpageScrollTo()
        }
    },
    // 关闭弹窗
    closeBox(e, num) {
        if (num == 1) {
            var index = 2; //1关闭全部弹窗   2关闭当前弹窗
        } else {
            var index = e.currentTarget.dataset.index; //1关闭全部弹窗   2关闭当前弹窗
        }
        // 1查询病历 2检验检查 3健康指导意见单 4查询图片 5人体示意 6住院建议书 7问诊规范 8结束问诊 9开处方 10修改患者资料 11分诊  12常用语 13 测量数据 
        //14查询历史问诊 15开处方-选择开药 16 开处方-生成处方 17检验检查-心电图 18检验检查-申请单  19健康指导-健康指导意见单详情填写 20填写诊断信息、主诉、过敏史等 21药品信息 22 保存模板 23处方详情 24 检验检查详情 25健康指导详情 26住院建议详情
        var This_openPageBox = 0
        if (index == 1) {
            This_openPageBox = 0
        } else {
            if (thenS_.openPageBox == 14) { //查询历史问诊  返回上一弹窗 测量数据
                This_openPageBox = 1
            } else if (thenS_.openPageBox == 15) { //开处方-选择开药  返回上一弹窗 开处方
                This_openPageBox = 9
            } else if (thenS_.openPageBox == 16) { //开处方-生成处方  返回上一弹窗 开处方-选择开药
                This_openPageBox = 15
            } else if (thenS_.openPageBox == 17 || thenS_.openPageBox == 18) { //检验检查-申请单  返回上一弹窗 检验检查
                This_openPageBox = 2
            } else if (thenS_.openPageBox == 19) { //
                This_openPageBox = 3
            } else if (thenS_.openPageBox == 20 || thenS_.openPageBox == 21 || thenS_.openPageBox == 22 || thenS_.openPageBox == 23 || thenS_.openPageBox == 24 || thenS_.openPageBox == 25 || thenS_.openPageBox == 28 || thenS_.openPageBox == 31) { // 返回上一弹窗 
                This_openPageBox = thenS_.openPageBox_up
                // 判断是否有住院建议书备注
                if (thenS_.openPageBox == 20) {
                    let bz = $service.getStore('zyjys_bz');
                    if (bz) {
                        this.setData({
                            zyjys_bz: bz
                        })
                    }
                }
            } else {
                // 清楚住院建议书备注缓存
                if (thenS_.openPageBox == 6) {
                    $service.removeStore('zyjys_bz')
                }
                if (thenS_.openPageBox == 29) {
                  wx.redirectTo({
                    url: '/pages/chat/doctor_chat/doctor_chat?isAuto=1',
                  })
                }
                This_openPageBox = this.data.isAuto == 0 ? 0 : 9
            }
        }
        if (This_openPageBox == 0) {
            this.bottom()
        }
        this.setData({
            openPageBox: This_openPageBox,
            bcmb_type: 0,
            bcmb_icd_id: '', //保存模板分类id
            bcmb_icd_name: '', //分类名称
            bcmb_bz: '', //备注
            bcmb_prescription_price: '0', //处方价格
            bcmb_prescription_name: '', //处方名称
            bcmb_prescription_taking: '', //服用方法
            bcmb_prescription_requirements: '', //服用要求
            bcmb_prescription_num: '', //付数
            bcmb_list: [],
            bcmb_list2: [],
            bcmb_diagnosisList: [],
            bcmb_queryName: '',
            bcmb_isullist: false
        })
    },
    // ---------------- 聊天
    taplist(e) {
        var index = e.currentTarget.dataset.index;
        this.setData({
            islistshow: false,
            message: this.data.list[index].content
        })
        this.send() //发送消息
    },
    setToolType(e) {
        console.log(e)
        var index = e.currentTarget.dataset.index
        if (index == "3") {
            this.data.teduBoard.clear(false);
        } else {
            this.data.teduBoard.setToolType(index)
        }
    },
    inputFocus(e) {
        this.setData({
            isWithdrawShow: false
        })
        var inputHeight = 0
        if (e.detail.height) {
            let query = wx.createSelectorQuery();
            query.select('.increased').boundingClientRect(rect => {
                let clientHeight = rect.height;
                let clientWidth = rect.width;
                let ratio = 750 / clientWidth;
                let height = clientHeight * ratio;
                inputHeight = e.detail.height * 750 / wx.getSystemInfoSync().windowWidth - height
                this.setData({
                    inputHeight,
                    increase: false,
                    messageHeight: e.detail.height * 750 / wx.getSystemInfoSync().windowWidth + this.data.messageHeight - height
                })
                console.log(this.data.messageHeight , '高度')
                this.bottom()
            }).exec();
        }
    },
    inputBlur() {
        this.getMessageheight()
        this.setData({
            inputHeight: 0,
            increase: false
        })
    },
    onPullDownRefresh() {
        page = 1;
        this.setData({
            loadingText: '加载更多'
        })
        this.getalldo();
        wx.stopPullDownRefresh()
    },
    onReachBottom: function () {
        if (thenS_.loadingType == true) {
            page++
            this.getalldo();
        } else {
            this.setData({
                loadingText: '没有更多了'
            })
        }
        // 廉江his病历列表上拉加载
        if (this.data.openPageBox == 14 && inqiuryLoading) {
          clinicPage ++
          this.getInquiryLogByUserIdList()
        }
    },
    loading() {
        if (thenS_.loadingType == true) {
            page++
            this.getalldo()
        } else {
            this.setData({
                loadingText: '没有更多了'
            })
        }
    },
    getalldo() { // 1查询病历 2检验检查 3健康指导意见单 4查询图片 5人体示意 6住院建议书 7问诊规范 8结束问诊 9开处方 10修改患者资料 11分诊  12常用语 13 测量数据 14查询历史问诊 15开处方-选择开药 16 开处方-生成处方 17检验检查-心电图 18检验检查-申请单  19健康指导-健康指导意见单详情填写 20填写诊断信息、主诉、过敏史等 21药品信息 22 保存模板 23处方详情 24 检验检查详情 25健康指导详情 26住院建议详情
        if (thenS_.openPageBox == 7) {
            this.doctorSide_personal_inquiry_getSpecification()
        }
        if (thenS_.openPageBox == 13) { //测量数据
            this.publicUtil_getPatientMeasuredDataList('now');
            this.publicUtil_getPatientMeasuredDataList('history');
        }
        if (thenS_.openPageBox == 15) { //15开处方-选择开药 
            if (thenS_.tapactive == 1 || thenS_.tapactive == 2) {
                // 药品目录和分类
                this.getDrugClass();
                this.getDrugList(0);
            } else if (thenS_.tapactive == 3) {
              this.data.paymentMethodNum == 0 ? this.getDrugList(1) : ''
            } else if (thenS_.tapactive == 4) {
              this.data.paymentMethodNum == 0 ? this.getPrescriptionTemplateList(0) : ''
            } else if (thenS_.tapactive == 5) {
                this.data.paymentMethodNum == 0 ? this.getPrescriptionTemplateList(1) : ''
            } else if (thenS_.tapactive == 6) {
              if (this.data.storeData.group_no != 0) {
                this.data.paymentMethodNum == 0 ? this.getOpenedPrescription() : ''
              }
            }
        }

    },

    //--------------------- 测量数据
    //获取历史和本次测量数据
    publicUtil_getPatientMeasuredDataList: function (type) {
        let params = {
            "current": page,
            "size": 10
        }
        if (type == 'now') {
            params.logId = Number(logId)
        } else {
            params.identityCard = this.data.inquiryMap.patientIdcard
        }
        app.http.getMeasureDataList(params).then(res => {
            let measuredDataList = [];
            if (type == 'now') {
                thenS_.measuredDataMap = res.data.list[0]
            } else {
                measuredDataList = res.data.list
                if (page == 1) {
                    thenS_.loadingText = '';
                    thenS_.measuredDataList = measuredDataList;
                } else {
                    if (measuredDataList.length <= 0) {
                        thenS_.loadingType = false;
                        thenS_.loadingText = '没有更多了';
                    } else {
                        for (var i = 0; i < measuredDataList.length; i++) {
                            thenS_.measuredDataList.push(measuredDataList[i]);
                            thenS_.loadingText = '加载更多';
                        }
                    }
                }
            }
            this.setData({
                measuredDataMap: thenS_.measuredDataMap,
                measuredDataList: thenS_.measuredDataList,
                loadingText: thenS_.loadingText,
                loadingType: thenS_.loadingType
            })
        }).catch(err => {
            $service.showToast(err.msg)
        })
    },


    // ----------------------- 图片列表
    getChatImages(id) {
        app.http.getChatImages({
            logId: Number(id),
            userIm: Number(imId)
        }).then(res => {
            this.setData({
                timeList: res.data.list,
            })
        }).catch(err => {
            $service.showToast(err.msg)
        })
    },
    previewImage: function (e) { //图片放大
        var index = e.currentTarget.dataset.index;
        var num = e.currentTarget.dataset.num;
        var all = [];
        if (num == 1) {
            all.push(this.data.timeList[index].msgContent);
        } else if (num == 2) {
            all.push(this.data.prescription_imgurl);
        } else if (num == 3) {
            all.push(this.data.checklist_imgurl);
        } else if (num == 4) {
            all.push(this.data.guidance_imgurl);
        } else if (num == 5) {
            all.push(this.data.hospitalization_imgurl);
        } else if (num == 6) {
            all.push(this.data.application_imgurl);
        }
        all.forEach(item => {
            item = item.replace(/https/, 'http')
        })
        wx.previewImage({
            urls: all
        })
    },


    // ------------------------------ 历史病例查询
    lookdetalis() {
        this.getpageScrollTo()
        this.getInquiryLogByUserIdList()
        thenS_.openPageBox_up = thenS_.openPageBox;
        this.setData({
            openPageBox: 14,
            openPageBox_up: thenS_.openPageBox_up
        })
    },
    //病例查询-问诊历史
    getInquiryLogByUserIdList() {
        if (this.data.hisType) {
          this.getClinicHistoryList()
          return
        }
        if (!$service.isEsgin) {
          let params = {
              "current": clinicPage,
              "identityCard": thenS_.inquiryMap.patientIdcard,
              "size": 10
          }
          app.http.getInquiryLogByUserIdList(params).then(res => {
              if (res.data && res.data.total > this.data.wzlslist.length) {
                let list = [...this.data.wzlslist, ...res.data.list]
                this.setData({
                  wzlslist: list
                })
              } else {
                inqiuryLoading = false
              }
          }).catch(err => {
              $service.showToast(err.msg)
          })
        }
    },
    doctorSide_personal_inquiry_getPatientHistoryInquiryLog: function () {
        var jsonData = {
            "inquiry_patient_id": inquiry_patient_id
        }
        var jsonAjax = {
            "url": "doctorSide_personal_inquiry_getPatientHistoryInquiryLog.do",
            "jsonData": jsonData,
        }
        $service.getAjaxData(jsonAjax, this.doctorSide_personal_inquiry_getPatientHistoryInquiryLog_back);
    },
    //回调
    doctorSide_personal_inquiry_getPatientHistoryInquiryLog_back: function (jsonBack) {
        var data = $service.strToJson(jsonBack.data).data;
        var list = data.inquiryLogList; //诊断结果
        for (var i = 0; i < list.length; i++) {
            list[i].lrsj2 = $service.nothinglrsj(list[i].lrsj)
        }
        this.setData({
            wzlslist: list
        })
    },
    // 查看已开报告
    wzlsgotodetalis(e) {
        var index = e.currentTarget.dataset.index;
        var num = e.currentTarget.dataset.num;
        var z = e.currentTarget.dataset.upindex;
        thenS_.openPageBox_up = thenS_.openPageBox;
        if (index == 1) { //检验检查
            thenS_.openPageBox = 24
            this.getEstablishPdf(thenS_.wzlslist[z].inspectionOpinion[num].id, 3)
        } else if (index == 2) { //健康指导
            thenS_.openPageBox = 25
            this.getEstablishPdf(thenS_.wzlslist[z].healthGuidance[num].id, 2);
        } else if (index == 3) { //住院建议
            thenS_.openPageBox = 26
            console.log('住院建议')
            this.getEstablishPdf(thenS_.wzlslist[z].hospitalization.inquiryPatientId, 1)
        } else if (index == 4) { //处方
            thenS_.openPageBox = 23;
            this.setData({
                syncFlag: false
            })
            this.getEstablishPdf(thenS_.wzlslist[z].inquiryLogPrescription[num].id, 4)
        } else if (index == 5) { //查看图片
            let imgList = []
            imgList = this.data.wzlslist[z].mediaMaterials.map(item => item.src)
            imgList.forEach(item => {
                item = item.replace(/https/, 'http')
            })
            wx.previewImage({
                urls: imgList // 需要预览的图片http链接列表
            })
        } else if (index == 6) { // 申请单
            thenS_.openPageBox = 28
            this.getEstablishPdf(thenS_.wzlslist[z].applicationForm[num].id, 5, thenS_.wzlslist[z].applicationForm[num].templateValue)
        }
        this.setData({
            openPageBox: thenS_.openPageBox,
            openPageBox_up: thenS_.openPageBox_up
        })
        this.getpageScrollTo()
    },
    //开处方、
    //数据
    gotodetalis(e) {
        if (this.data.isAuto == 1 && !logId) {
          $service.showToast('请先填写就诊人信息')
          return
        }
        var index = e.currentTarget.dataset.index;
        thenS_.openPageBox_up = thenS_.openPageBox;
        if (index == 0 || index == 1 || index == 2 || index == 3 || index == 4) { //0过敏史 1 主诉 2现病史 3既往史 4诊断
            thenS_.openPageBox = 20
            thenS_.tabactive = index;
            if (e.index == 0) {
                this.data.text = thenS_.inquiryMap.patientAllergyDetails
            } else if (e.index == 1) {
                this.data.text = thenS_.inquiryMap.mainSuit
            } else if (e.index == 2) {
                this.data.text = thenS_.inquiryMap.presentIllness
            } else if (e.index == 3) {
                this.data.text = thenS_.inquiryMap.historyPresentIllness
            } else if (e.index == 4) {}
            this.setData({
                tabactive: thenS_.tabactive,
                text: this.data.text,
                txdiagnosis_iinquiry_patient_allergy_details: thenS_.inquiryMap.patientAllergyDetails, //过敏史
                txdiagnosis_log_main_suit: thenS_.inquiryMap.mainSuit, //主诉
                txdiagnosis_log_present_illness: thenS_.inquiryMap.presentIllness, //现病史
                txdiagnosis_log_history_present_illness: thenS_.inquiryMap.historyPresentIllness, //既往史
                txdiagnosis_lof_diagnosis: thenS_.inquiryMap.diagnosis //诊断
            })
            this.getdoctorSide_personal_inquiry()
            this.getlofdiagnosis(thenS_.inquiryMap.diagnosis, 1)
        } else if (index == 5) {
            var num = e.currentTarget.dataset.num;
            thenS_.openPageBox = 23;
            this.setData({
                syncFlag: true
            })
            this.getEstablishPdf(thenS_.prescriptionList[num].id, 4)
            // this.publicUtil_getInquiryLogPrescriptionDetails(thenS_.prescriptionList[num].id)
        } else if (index == 6 || index == 7) { //中西药开方
            if ($service.isUndefinedAndEmpty(thenS_.inquiryMap.mainSuit)) {
                $service.showToast("请先输入主诉")
                return;
            }
            if ($service.isUndefinedAndEmpty(thenS_.inquiryMap.diagnosis)) {
                $service.showToast("请先输入诊断")
                return;
            }
            if (index == 6) {
                thenS_.drug_type = "2"
            } else {
                thenS_.drug_type = "1"
            }
            thenS_.openPageBox = 15;
        }

        if (index == 6 || index == 7) {
            // 重置药品筛选条件
            this.setData({
                drug_name: '',
                class_name: '',
                class_id: '',
                tapactive: "1",
                shopId: '',
                storeData: {}
            })
            if (this.data.paymentMethodNum == 1) { // 如果是医保处方默认选择药店
              this.data.storeData = {
                group_name: this.data.hisType ? '院内药店' :'医保平台',
                group_no: 0,
              }
            } else {
              this.data.storeData = []
            }
            this.setData({
              storeData: this.data.storeData
            })
            page = 1
            this.getalldo()
        }
        this.setData({
            openPageBox: thenS_.openPageBox,
            openPageBox_up: thenS_.openPageBox_up,
            drug_type: thenS_.drug_type,
        })
        this.getpageScrollTo()
    },
    //删除处方
    deletImg(e) {
        var this_ = this
        var index = e.currentTarget.dataset.index;
        wx.showModal({
            title: '温馨提示',
            content: '确定要将此处方作废？',
            success: (res) => {
                if (res.confirm) {
                    console.log(thenS_.prescriptionList[index].id)
                    app.http.deletePrescription({
                        id: thenS_.prescriptionList[index].id
                    }).then(res => {
                        $service.showToast(res.msg)
                        this_.publicUtil_getInquiryLogDetails()
                    }).catch(err => {
                        $service.showToast(err.msg)
                    })
                }
            }
        })
    },


    // ---------------- 选择处方
    //西药、中药列表、分类，个人
    getDrugList(isPublic = 0) {
        if (this.data.hisType && this.data.storeData.group_no == 0) { //如果是廉江his 并且选择了院内处方
          this.getHisDrugInfoList(thenS_.drug_type, page)
          return
        }
        if (this.data.paymentMethodNum == 0) {
            var params = {
                "drugType": Number(thenS_.drug_type),
                "classId": thenS_.class_id,
                "current": Number(page),
                "drugName": thenS_.drug_name,
                "shopId": thenS_.shopId || null,
                "size": 50,
                "isPublic": String(isPublic),
            }
            app.http.getDrugList(params).then(res => {
                var drugList = res.data.list;
                if (drugList) {
                    for (var i = 0; i < drugList.length; i++) {
                        drugList[i].drug_usname = $service.nothingFun(drugList[i].drug_usname, '--')
                    }
                }
                //判断选项卡情况
                if (thenS_.tapactive == 1) {
                    if (page == 1) {
                        thenS_.loadingText = '';
                        thenS_.drugList = drugList;
                        thenS_.loadingType = true;
                    } else {
                        if (!drugList || drugList.length == 0) {
                            thenS_.loadingType = false;
                            thenS_.loadingText = '没有更多了';
                        } else {
                            for (var i = 0; i < drugList.length; i++) {
                                thenS_.drugList.push(drugList[i]);
                                thenS_.loadingText = '加载更多';
                            }
                        }
                    }
                } else {
                    thenS_.loadingText = '';
                    thenS_.drugList = drugList;
                    thenS_.loadingType = true;
                }
                if (isPublic === 0) {
                    this.setData({
                        drugList: thenS_.drugList,
                    })
                } else {
                    this.setData({
                        drugList2: thenS_.drugList,
                    })
                }
                this.setData({
                    loadingText: thenS_.loadingText,
                    loadingType: thenS_.loadingType,
                })
            }).catch(err => {
                $service.showToast(err.msg);
            })
        } else {
            // 医保获取药品列表用这个
              var drugName = this.data.drug_name
              var params = {
                  "medicineName": drugName == "" ? "" : drugName,
                  "pageNo": Number(page),
                  "pageSize": 20,
              }
              // 珠海医保药品列表
              app.http.medicineList(params).then(res => {
                  // var drugList = res.data.list; //药品列表
                  var dataList = res.data.medicineListVOList; //药品列表(医保)
                  var drugList = []
                  dataList.forEach((item, index) => {
                      drugList.push({
                          // alias:"",
                          // aliasName:"",
                          // drugCompany:"",
                          // drugImg:"",
                          // drugInstructions:"",
                          // drugPackagingNum:"",
                          // drugPackagingUnit:"",
                          // drugPrice:"",
                          drugpype: item.type,
                          // drugSmallestUnit:"",
                          // drugTemplateId:"",
                          id: item.id,
                          // identification:"",
                          // placeOriin:"",
                          // storeId:"",
                          drug_usname: item.norms,
                          drugName: item.name,
                          drugSpecifications: item.drugSpecification,
                          // drugUnit:item,unit,
                          storeName: item.manufacturer,
                          drugCommonCode: item.drugCommonCode,
                          approvalNum: item.approvalNum,
                          drugPackagingUnit: item.unit
                      })
                  })
                  console.log(drugList);
                  if (drugList) {
                      for (var i = 0; i < drugList.length; i++) {
                          drugList[i].drug_usname = $service.nothingFun(drugList[i].drug_usname, '--')
                      }
                  }
                  //判断选项卡情况
                  if (thenS_.tapactive == 1) {
                      if (page == 1) {
                          thenS_.loadingText = '';
                          thenS_.drugList = drugList;
                          thenS_.loadingType = true;
                      } else {
                          if (!drugList || drugList.length == 0) {
                              thenS_.loadingType = false;
                              thenS_.loadingText = '没有更多了';
                          } else {
                              for (var i = 0; i < drugList.length; i++) {
                                  thenS_.drugList.push(drugList[i]);
                                  thenS_.loadingText = '加载更多';
                              }
                          }
                      }
                  } else {
                      thenS_.loadingText = '';
                      thenS_.drugList = drugList;
                      thenS_.loadingType = true;
                  }
                  if (isPublic === 0) {
                      this.setData({
                          drugList: thenS_.drugList,
                      })
                  } else {
                      this.setData({
                          drugList2: thenS_.drugList,
                      })
                  }
                  this.setData({
                      loadingText: thenS_.loadingText,
                      loadingType: thenS_.loadingType,
                  })
              }).catch(err => {
                  $service.showToast(err.msg);
              })
        }
    },
    // 获取药品类型
    getDrugClass() {
        app.http.getDrugClass().then(res => {
            res.data.unshift({
                id: '',
                className: '全部'
            })
            this.setData({
                drugClassList: res.data
            })
        }).catch(err => {
            $service.showToast(err.msg);
        })
    },

    //个人、公共模板
    getPrescriptionTemplateList(isPublic) {
        if (this.data.hisType && this.data.storeData.group_no == 0) {
          return
        }
        let params = {
            "isPublic": isPublic,
            "prescriptionType": thenS_.drug_type
        }
        app.http.getPrescriptionTemplateList(params).then(res => {
            console.log(res);
            var drugList = res.data.list; //列表
            // if (page == 1) {
            thenS_.loadingText = '';
            thenS_.drugList3 = drugList;
            // for (var i = 0; i < thenS_.drugList3.length; i++) {
            //     thenS_.drugList3[i].drugList[0].storeId = thenS_.drugList3[i].storeId;
            //     thenS_.drugList3[i].drugList[0].storeName = thenS_.drugList3[i].storeName
            // }
            this.setData({
                drugList3: thenS_.drugList3,
                loadingText: thenS_.loadingText,
                loadingType: thenS_.loadingType
            })
        }).catch(err => {
            $service.showToast(err.msg)
        })
    },
    //历史处方
    getOpenedPrescription() {
        let params = {
            // "inquiryPatientId": inquiryPatientId,
            // "logId": logId,
            "prescriptionType": thenS_.drug_type
        }
        app.http.getOpenedPrescription(params).then(res => {
            console.log(res)
            var drugList = res.data.list; //列表
            this.setData({
                drugList4: drugList,
            })
        }).catch(err => {
            $service.showToast(err.msg);
        })
    },
    //用药tab切换
    taptab(e) {
        var index = e.currentTarget.dataset.index;
        if (this.data.tapactive != 2) {
            thenS_.class_id = ''
            thenS_.class_name = '全部'
        } else {
            if (!thenS_.drugClassList) {
                thenS_.class_id = ''
                thenS_.class_name = ''
            } else {
                if (thenS_.drug_type == 2) {
                    // thenS_.class_id = thenS_.drugClassList[0].id
                    // thenS_.class_name = thenS_.drugClassList[0].className
                }
            }
        }
        this.setData({
            tapactive: index,
            drugList: [],
            drugList2: [],
            drugList3: [],
            drugList4: [],
            class_id: thenS_.class_id,
            drug_name: '',
            class_name: thenS_.class_name
        })
        page = 1
        this.getalldo()
    },
    //分类选择
    tapisshow(e) {
        this.data.isshow = !this.data.isshow;
        this.setData({
            isshow: this.data.isshow
        })
    },
    tapchoose(e) {
        var index = e.currentTarget.dataset.index;
        this.data.isshow = !this.data.isshow;
        if (index == -1) {
            thenS_.class_id = '',
                thenS_.class_name = '全部'
        } else {
            console.log(thenS_.drugClassList[index])
            thenS_.class_id = thenS_.drugClassList[index].id,
                thenS_.class_name = thenS_.drugClassList[index].className
        }
        this.setData({
            isshow: this.data.isshow,
            class_id: thenS_.class_id,
            class_name: thenS_.class_name
        })
        page = 1
        this.getalldo()
    },
    //药品分类picker
    sortPickerChange(e) {
        thenS_.class_id = thenS_.drugClassList[e.detail.value].id
        thenS_.class_name = thenS_.drugClassList[e.detail.value].className
        this.setData({
            valueIndex: e.detail.value,
            class_id: thenS_.class_id,
            class_name: thenS_.class_name
        })
        console.log(this.data.class_name);
        page = 1
        this.getalldo()
    },
    //药品分类判断
    sortPicker(e) {
        if (this.data.storeData.group_no == 0 && this.data.hisType) {
          $service.showToast("院内药店暂无设置分类筛选")
          return
        }
        if (this.data.paymentMethodNum == 1) {
            $service.showToast("医保单暂无设置分类筛选")
        } else {
            this.setData({
                isPickerShow: false
            })
        }
    },
    //西药分类picker
    wmSortPickerChange(e) {
        thenS_.class_id = thenS_.drugClassList[e.detail.value].id
        thenS_.class_name = thenS_.drugClassList[e.detail.value].className
        this.setData({
            wmValueIndex: e.detail.value,
            class_id: thenS_.class_id,
            class_name: thenS_.class_name
        })
        console.log(this.data.class_name);
        page = 1
        this.getalldo()
    },
    //药品来源分类
    changeStore(e) {
        this.setData({
            shopId: e.detail.group_no,
            storeData: e.detail
        })
        page = 1
        this.getalldo()
    },
    storePickerChange(e) {
        // thenS_.class_id = thenS_.drugClassList[e.detail.value].id
        // thenS_.class_name = thenS_.drugClassList[e.detail.value].className
        thenS_.shopId = thenS_.doctorStoreList[e.detail.value].group_no
        this.setData({
            storeIndex: e.detail.value,
            shopId: thenS_.shopId
        })
        // console.log(this.data.class_name);
        page = 1
        this.getalldo()
    },
    //西药药品来源
    wmstorePickerChange(e) {
        // thenS_.class_id = thenS_.drugClassList[e.detail.value].id
        // thenS_.class_name = thenS_.drugClassList[e.detail.value].className
        thenS_.shopId = thenS_.doctorStoreList[e.detail.value].group_no
        this.setData({
            wmstoreIndex: e.detail.value,
            shopId: thenS_.shopId
        })
        page = 1
        this.getalldo()
    },

    xzypinputChange(e) {
        this.setData({
            drug_name: e.detail.value
        })
        page = 1
        this.getalldo()
    },
    //点击按钮
    async tapdrugList(e) {
        var this_ = this;
        var type = e.currentTarget.dataset.type; //0目录、分类 1个人用药 2个人、公共模板 3历史处方
        var index = e.currentTarget.dataset.index; //下标
        this.setData({
            medListIndex: index
        })
        var num = e.currentTarget.dataset.num; //1保存用药
        thenS_.openPageBox_up = thenS_.openPageBox;
        if (num == 1) { //1保存用药
            console.log(this.data.drugList);
            app.http.addPersonalDrug({
                id: this.data.drugList[index].id,
                drugType: Number(this.data.drug_type)
            }).then(res => {
                $service.showToast(res.msg);
            }).catch(err => {
                $service.showToast(err.msg);
            })
        } else if (num == 2) { //详情
            if (type == 0) {
                var id = this.data.drugList[index].id
            } else if (type == 1) {
                var id = this.data.drugList2[index].id
            } else if (type == 4) {
                var id = this.data.diagnosisMap.drugList[index].id
            }
            thenS_.openPageBox = 21
            this.publicUtil_getDrugDetail(id)
        } else if (num == 3) { //开药
            if (type == 0) {
                var drugMap = this.data.drugList[index]
            } else if (type == 1) {
                var drugMap = this.data.drugList2[index]
            }
            // 成都大医来判断是否为禁用药品
            if ($service.isEsgin) {
              if (!await this.isDrugDisable(drugMap.id)) return
            }
            thenS_.openPageBox = 16;
            this.setData({
                drugMap: drugMap,
                sccfisshow: 1,
                details_usage: '', //用法
                details_consumption: '', //用量
                details_consumption_util: '', //用量单位
                details_frequency: '', ///频率,
                details_frequency_str: '',
                details_frequency_str2: '',
                details_day: '', //天数
                details_num: '', //盒数
                detailsEntrust: '', //嘱托
                islist: false, //弹窗显示隐藏
                islist2: false, //弹窗显示隐藏
                islist3: false, //弹窗显示隐藏
                isconsumptionlist: false, //弹窗显示隐藏
                drug_packaging_unit: '', //盒数单位
                getdruglistStoragelist: [], //已选处方
                prescription_price: 0, //处方金额
                prescription_taking: '', //服用方法
                prescription_requirements: '', //服用要求
                prescription_num: '', //付数
                prescription_isdetalis: false, //生成中药弹窗
                frequency_num: 0,
                frequency_day_num: 0,
                selectionunit: 0,
                drug_packaging_num: 1

            })
            this.getpageScrollTo()
            this.publicUtil_getInquiryLogDetails()
            this.publicUtil_getDrugDetail2('1') //药品详情
            this.getdruglistStorage()
        } else if (num == 4) { //删除个人用药/个人模板
            if (type == 1) {
                var drugMap = this.data.drugList2[index]
                console.log(drugMap);
                var content = '确定要删除当前常用药品？'
            } else if (type == 2) {
                var drugMap = this.data.drugList3[index]
                var content = '确定要删除当前常用模板？'
            }
            wx.showModal({
                title: '温馨提示',
                content: content,
                success(res) {
                    if (res.confirm) {
                        if (type == 1) { //删除个人用药
                            app.http.deletePersonalDrug({
                                id: thenS_.drugList2[index].drugTemplateId
                            }).then(res => {
                                page = 1
                                $service.showToast(res.msg)
                                this_.getalldo()
                            }).catch(err => {
                                $service.showToast(err.msg)
                            })
                        } else if (type == 2) { //删除个人模板
                            console.log(thenS_.drugList3[index])
                            app.http.deletePrescriptionTemplate({
                                id: thenS_.drugList3[index].id
                            }).then(res => {
                                page = 1
                                $service.showToast(res.msg)
                                this_.getalldo()
                            }).catch(err => {
                                $service.showToast(err.msg)
                            })
                        }
                    }
                }
            })
        } else if (num == 5 || num == 6 || num == 7) { //引用处方5 //查看模板6 7另存模板
            tapMap_type = 0
            if (type == 2) { //模板的
                thenS_.diagnosisMap = thenS_.drugList3[index]
            } else if (type == 3) { //历史处方的
                thenS_.diagnosisMap = thenS_.drugList4[index];
                thenS_.diagnosisMap.drugList = thenS_.drugList4[index].detailsResps
            }
            if (num == 5) {
                if (this.data.drug_type == 1) { //已选中 中药 、、存缓存
                    druglistStorage_z = [];
                    druglistStorage_z = type == 2 ? thenS_.drugList3[index].drugList : thenS_.drugList4[index].drugList
                    // let {prescriptionTaking, prescriptionRequirements, prescriptionNum} = type == 2 ? thenS_.drugList3[index] : thenS_.drugList4[index]
                    // this.setData({
                    //     prescription_taking: prescriptionTaking,
                    //     prescription_requirements: prescriptionRequirements,
                    //     prescription_num: prescriptionNum
                    // })
                    wx.setStorageSync("druglistStorage_z" + doctorId, JSON.stringify(druglistStorage_z))
                } else { //已选中 西药 、、存缓存
                    druglistStorage_x = [];
                    druglistStorage_x = type == 2 ? thenS_.drugList3[index].drugList : thenS_.drugList4[index].drugList
                    wx.setStorageSync("druglistStorage_x" + doctorId, JSON.stringify(druglistStorage_x))
                }
                $service.showToast('引用成功')
            } else if (num == 6) {
                tapMap_type = 1;
                this.setData({
                    diagnosisMap: thenS_.diagnosisMap,
                    isdetalis: true
                })
            } else if (num == 7) {
                tapMap_type = 2;
                thenS_.openPageBox_up = thenS_.openPageBox;
                this.setData({
                    openPageBox: 22,
                    openPageBox_up: thenS_.openPageBox_up,
                    bcmb_type: 0
                })
                this.getpageScrollTo()
                template_prescriptionList = {
                    detailsList: thenS_.drugList4[index].detailsResps,
                    prescription_price: Number(thenS_.drugList4[index].prescriptionPrice).toFixed(2),
                    storeId: thenS_.drugList4[index].storeId,
                    storeName: thenS_.drugList4[index].storeName,
                    preType: 2,
                }
                this.publicUtil_getUtilTable78()
            }
        } else if (num == 8) { //关闭弹窗
            this.setData({
                isdetalis: false
            })
        } else if (num == 9) {
            thenS_.openPageBox = 16
            this.getdruglistStorage()
            this.setData({
                sccfisshow: 0
            })
        }
        this.setData({
            openPageBox: thenS_.openPageBox,
            openPageBox_up: thenS_.openPageBox_up
        })
    },
    // 检查是否为禁用药品
    async isDrugDisable(id) {
      try {
        await app.http.isDrugDisable({drugId: id})
        return true
      } catch (err) {
        $service.showToast(err.msg)
        return false
      }
    },
    //  ---------------- 生成处方
    //问诊详情
    getdruglistStorage() {
        if (thenS_.drug_type == 1) { //1中药
            if (!$service.isUndefinedAndEmpty(wx.getStorageSync("druglistStorage_z" + doctorId))) {
                var list = $service.strToJson(wx.getStorageSync("druglistStorage_z" + doctorId));
            } else {
                var list = []
            }
            druglistStorage_z = list; //已选中药处方 列表

        } else if (thenS_.drug_type == 2) {
            if (!$service.isUndefinedAndEmpty(wx.getStorageSync("druglistStorage_x" + doctorId))) {
                var list = $service.strToJson(wx.getStorageSync("druglistStorage_x" + doctorId));
            } else {
                var list = []
            }
            druglistStorage_x = list; //已选西药处方 列表
        }
        var drug_price = 0;
        for (var i = 0; i < list.length; i++) {
            if ($service.isUndefinedAndEmpty(list[i].drugPrice)) {
                list[i].drugPrice = 0
            }
            drug_price += $service.strToFloat(list[i].drugPrice) * $service.strToInt(list[i].detailsNum);
            // if (thenS_.drug_type == 1) { //1中药
            //     drug_price+=$service.strToFloat(list[i].drugPrice)*$service.strToInt(list[i].detailsConsumption);
            // }else{
            //     drug_price+=$service.strToFloat(list[i].drugPrice)*$service.strToInt(list[i].detailsNum);
            // }
        }
        this.setData({
            getdruglistStoragelist: list,
            prescription_price: Number(drug_price).toFixed(2)
        })
    },
    // ------药品频次 用法要求 工具
    //  频次
    getDrugFrequencyList() {
        app.http.getDrugFrequencyList().then(res => {
            this.setData({
                list2: res.data.list
            })
        })
    },
    // 用法
    getDrugUsageList(usageType) {
        app.http.getDrugUsageList({
            usageType: usageType
        }).then(res => {
            switch (usageType) {
                case 1:
                    thenS_.list = res.data.list
                    break;
                case 2:
                    thenS_.list = [...[{id: 0, usageName: '无'}],...res.data.list]
                    break;
                case 3:
                    thenS_.list2 = res.data.list
                    break;
                case 4:
                    thenS_.list3 = res.data.list
                    break;
            }
            this.setData({
                list: thenS_.list,
                list2: thenS_.list2,
                list3: thenS_.list3
            })
        })
    },
    publicUtil_getInquiryLoggetUtilTable: function () {
        if (this.data.hisType && this.data.storeData.group_no == 0) { // 廉江his用法
          if (this.data.drug_type == 1) { // 中药
            this.getDictInfo(70)
            this.getDictInfo(52)
          } else { // 西药
            this.getDictInfo(51)
            this.getDictInfo(60)
          }
          this.getDictInfo(20)
          return
        }
        if (thenS_.drug_type == 2) {
            this.getDrugUsageList(1)
            this.getDrugFrequencyList();
        } else {
            this.getDrugUsageList(2)
            this.getDrugUsageList(3)
            this.getDrugUsageList(4)
        }
    },
    //药品详情
    publicUtil_getDrugDetail2: function (type) { // 1是开药 2是编辑
        if (this.data.hisType && this.data.storeData.group_no == 0) { // 廉江his药品
          let drugMap = this.data.drugMap
            if (type === '1') { // 开要设置默认用法
              this.publicUtil_getInquiryLoggetUtilTable() //工具
                this.setData({
                    details_usage: this.data.drug_type == "1" ? drugMap.decocteName || '' : drugMap.defaultUsageName || "",
                    details_consumption: drugMap.defaultDose || "",
                    details_consumption_util: drugMap.doseUnitIame || '',
                    details_frequency_str2: drugMap.defaultFrequencyCode || "",
                    details_frequency: drugMap.defaultFrequencyId || "",
                    details_frequency_str: drugMap.defaultFrequencyCode || "",
                    // frequency_num: drugMap.frequencyNum || "", // 频次数
                    // frequency_day_num: drugMap.frequencyTime || "", // 频率时间间隔 
                    detailsEntrust: drugMap.enjoin || "",
                    details_day: drugMap.drugMaxday || "",
                    // selectionunit: drugMap.drugUnit ? '5' : '2' // 如果药品单位有则使用5的数据计算药品 没有则用2
                })
            }
            this.setData({
                // consumptionlist: drugMap.consumptionList,
                drug_packaging_unit: drugMap.packageUnitName,
                useUnit: drugMap.useUnit,
                // drugMap: drugMapList,
                // dosage: this.data.paymentMethodNum == 1 ? drugMap.dosage : '',
            })
          return 
        }
        var params = {
            "id": thenS_.drugMap.id
        }
        let api = this.data.paymentMethodNum == 1 ? 'medicineGetById' : 'getDrugInfo'
        app.http[api](params).then(res => {
            var drugMap = res.data;
            var drugMapList = this.data.drugMap;
            if (this.data.paymentMethodNum == 1) {
              drugMapList.goodsGuige = res.data.unit;
              drugMapList.goodsGuigeUnit = res.data.norms;
              drugMapList.drugSpecifications = res.data.norms;
              medicineObj = drugMap;
            } else {
              drugMapList.goodsGuige = res.data.goodsGuige;
              drugMapList.goodsGuigeUnit = res.data.goodsGuigeUnit;
              // this.data.drugList[index].goodsGuige = res.data.goodsGuige;
            }
            medicineObj = drugMap;
            if (type === '1') { // 开要设置默认用法
              this.publicUtil_getInquiryLoggetUtilTable() //工具
              this.setData({
                  details_usage: this.data.drug_type == "1" ? drugMap.usageType : drugMap.drugUsage || "",
                  details_consumption: drugMap.usageNum || "",
                  details_consumption_util: drugMap.useUnit || drugMap.drugVolumeUnit,
                  details_frequency_str2: $service.hospitalType != 'yihan' ? drugMap.frequency || "" : '',
                  details_frequency: $service.hospitalType != 'yihan' ? drugMap.frequencyId || "" : '',
                  details_frequency_str: $service.hospitalType != 'yihan' ?  drugMap.frequencyName || "" : '',
                  frequency_num: $service.hospitalType != 'yihan' ? drugMap.frequencyNum || "" : '', // 频次数
                  frequency_day_num: $service.hospitalType != 'yihan' ? drugMap.frequencyTime || "" : '', // 频率时间间隔 
                  detailsEntrust: drugMap.enjoin || "",
                  details_day: drugMap.drugMaxday || "",
                  selectionunit: drugMap.drugUnit ? '5' : '2' // 如果药品单位有则使用5的数据计算药品 没有则用2
              })
              if (this.data.drug_type == "2") this.jisuanxiyaochufangshuliang()
              }
              this.setData({
                  consumptionlist: drugMap.consumptionList,
                  drug_packaging_unit: drugMap.drugPackagingUnit,
                  useUnit: drugMap.useUnit,
                  drugMap: drugMapList,
                  dosage: this.data.paymentMethodNum == 1 ? drugMap.dosage : '',
              })
        }).catch(err => {
          $service.showToast(err.msg)
        })
    },
    tap_usage(e) {
        var num = e.currentTarget.dataset.index;
        if (this.data.paymentMethodNum == 0) {
            // if (thenS_.drugMap.goodsGuigeUnit != thenS_.drugMap.drugUnit) {
            //     $service.showToast('药品单位与药品规格单位不一致，请联系管理员处理后在重试');
            //     return;
            // } else {
            if (num == 0) { //用法
                thenS_.islist = !thenS_.islist
                thenS_.isconsumptionlist = false
                thenS_.islist2 = false
                thenS_.islist3 = false
            } else if (num == 1) { //用量单位
                thenS_.isconsumptionlist = !thenS_.isconsumptionlist
                thenS_.islist = false
                thenS_.islist2 = false
                thenS_.islist3 = false
            } else if (num == 2 || num == 4) { //频次
                thenS_.islist2 = !thenS_.islist2
                thenS_.isconsumptionlist = false
                thenS_.islist = false
                thenS_.islist3 = false
            } else if (num == 3 || num == 5) { //嘱托
                thenS_.islist3 = !thenS_.islist3
                thenS_.isconsumptionlist = false
                thenS_.islist = false
                thenS_.islist2 = false
            }
            this.setData({
                islist: thenS_.islist,
                islist2: thenS_.islist2,
                islist3: thenS_.islist3,
                isconsumptionlist: thenS_.isconsumptionlist
            })
            // }
        } else {
            if (num == 0) { //用法
                thenS_.islist = !thenS_.islist
                thenS_.isconsumptionlist = false
                thenS_.islist2 = false
                thenS_.islist3 = false
            } else if (num == 1) { //用量单位
                thenS_.isconsumptionlist = !thenS_.isconsumptionlist
                thenS_.islist = false
                thenS_.islist2 = false
                thenS_.islist3 = false
            } else if (num == 2 || num == 4) { //频次
                thenS_.islist2 = !thenS_.islist2
                thenS_.isconsumptionlist = false
                thenS_.islist = false
                thenS_.islist3 = false
            } else if (num == 3 || num == 5) { //嘱托
                thenS_.islist3 = !thenS_.islist3
                thenS_.isconsumptionlist = false
                thenS_.islist = false
                thenS_.islist2 = false
            }
            this.setData({
                islist: thenS_.islist,
                islist2: thenS_.islist2,
                islist3: thenS_.islist3,
                isconsumptionlist: thenS_.isconsumptionlist
            })
        }
    },
    //选择用法、用量单位、频次、嘱托
    chooselist(e) {
        var index = e.currentTarget.dataset.index;
        var num = e.currentTarget.dataset.num;
        let lianjiangStore = this.data.storeData.group_no == 0 && this.data.hisType // 是否是廉江院内药店
        if (num == 0) { //用法
            thenS_.details_usage = lianjiangStore ? thenS_.list[index].dictName : thenS_.list[index].usageName == '无' ? '' : thenS_.list[index].usageName
        } else if (num == 1) { //用量单位
            if (lianjiangStore ) { // 廉江his选择药品单位
              thenS_.details_consumption_util = thenS_.consumptionlist[index].dictName
            } else {
              thenS_.details_consumption_util = thenS_.consumptionlist[index]
              this.jisuanxiyaochufangshuliang()
            }
        } else if (num == 2) { //频次
            if (!lianjiangStore) {
              thenS_.details_frequency = thenS_.list2[index].id
              thenS_.details_frequency_str = thenS_.list2[index].frequencyPrintingName
              thenS_.details_frequency_str2 = thenS_.list2[index].frequencyName
              this.setData({ // 11
                  frequency_num: thenS_.list2[index].frequencyNum,
                  frequency_day_num: thenS_.list2[index].frequencyHoursNum
              });
              this.jisuanxiyaochufangshuliang()
            } else {  // 是否是廉江院内药店
              thenS_.details_frequency = thenS_.list2[index].dictCode
              thenS_.details_frequency_str = thenS_.list2[index].dictName
              thenS_.details_frequency_str2 = thenS_.list2[index].dictName
            }
        } else if (num == 3) { //嘱托
            thenS_.detailsEntrust = thenS_.list2[index].advice_name
        } else if (num == 4) { //服用方法
            thenS_.prescription_taking = thenS_.list2[index].usageName
        } else if (num == 5) { //服用要求
            thenS_.prescription_requirements = thenS_.list3[index].usageName
        }
        this.setData({
            details_usage: thenS_.details_usage,
            details_consumption_util: thenS_.details_consumption_util,
            details_frequency: thenS_.details_frequency,
            details_frequency_str2: thenS_.details_frequency_str2,
            details_frequency_str: thenS_.details_frequency_str,
            detailsEntrust: thenS_.detailsEntrust,
            prescription_taking: thenS_.prescription_taking,
            prescription_requirements: thenS_.prescription_requirements,
            islist: false,
            islist2: false,
            islist3: false,
            isconsumptionlist: false
        })
    },
    //填写用量
    writeUnit(e) {
        let value = e.detail.value;
        this.setData({
            details_consumption_util: value
        })
    },
    //input监听
    inputChange(e) {
        var index = e.currentTarget.dataset.index;
        if (index == 1) { //用量
            let reg = /^\d+(\.\d+)?$/;
            if (!reg.test(e.detail.value)) {
                $service.showToast('请输入正确的用量')
                thenS_.details_consumption = 1
            } else {
                thenS_.details_consumption = parseFloat(e.detail.value)
            }
        } else if (index == 2) { //天数
            thenS_.details_day = e.detail.value
        } else if (index == 3) { //盒数
            thenS_.details_num = e.detail.value
        } else if (index == 4) { //嘱托
            thenS_.detailsEntrust = e.detail.value
        } else if (index == 5) { //付数
            thenS_.prescription_num = e.detail.value
        }
        this.setData({
            details_consumption: thenS_.details_consumption,
            details_day: thenS_.details_day,
            details_num: thenS_.details_num,
            detailsEntrust: thenS_.detailsEntrust,
            prescription_num: thenS_.prescription_num
        })
    },
    //input监听
    inputChange2(e) {
        var index = e.currentTarget.dataset.index;
        if (index == 1) { //用量
            thenS_.details_consumption = e.detail.value
        } else if (index == 2) { //天数
            thenS_.details_day = e.detail.value
        } else if (index == 5) {
            thenS_.prescription_num = e.detail.value
        }
        this.setData({
            details_consumption: thenS_.details_consumption,
            details_day: thenS_.details_day,
            prescription_num: thenS_.prescription_num
        })
        if (index == 1) { //用量
            this.jisuanxiyaochufangshuliang()
        } else if (index == 2) { //天数
            this.jisuanxiyaochufangshuliang()
        }
    },
    tap_reduce_add(e) {
        var index = e.currentTarget.dataset.index;
        if ($service.isUndefinedAndEmpty(thenS_.details_consumption)) {
            thenS_.details_consumption = 0
        }
        if (index == 0) {
            thenS_.details_consumption--
            if (thenS_.details_consumption <= 0) {
                $service.showToast('用量不能小于0');
                thenS_.details_consumption = 1
            }
        } else {
            thenS_.details_consumption++
        }
        this.setData({
            details_consumption: thenS_.details_consumption
        })
    },
    //生成处方
    qrBtn(e) {
        var index = e.currentTarget.dataset.index;
        thenS_.openPageBox_up = thenS_.openPageBox;
        if (index == 1) { //生成已选处方（未开）
            var detailsList = []
            if ($service.isUndefinedAndEmpty(thenS_.details_consumption)) {
                $service.showToast('请先输入用量');
                return;
            }
            if (Number(thenS_.details_consumption) <= 0) {
                $service.showToast('请先输入正确用量');
                return;
            }
            if ($service.isUndefinedAndEmpty(thenS_.details_consumption_util)) {
                $service.showToast('请先选择用量单位');
                return;
            }
            if (thenS_.drugMap.goodsGuigeUnit) {
                // if (this.data.paymentMethodNum == 0) {
                //     if (thenS_.drugMap.goodsGuigeUnit != thenS_.details_consumption_util) {
                //         $service.showToast('药品单位与药品规格单位不一致，请联系管理员处理后在重试');
                //         return;
                //     }
                // } else {

                // }
            } 

            if (thenS_.drug_type == 1) { //1中药
                console.log(thenS_.details_consumption);
                console.log(thenS_.drugMap.goodsGuige);
                var details_num = Math.ceil(thenS_.details_consumption / (thenS_.drugMap.goodsGuige || 1));

                for (var i = 0; i < druglistStorage_z.length; i++) { //判断缓存是否有相同的，先删除再添加
                    if (druglistStorage_z[i].drugId == thenS_.drugMap.id) {
                        druglistStorage_z.splice(i, 1)
                    }
                }
                console.log(thenS_.drugMap)
                this.setData({
                    storeId: thenS_.drugMap.storeId,
                    storeName: thenS_.drugMap.storeName,
                })
                StorageJosn = {
                    "drugSpecifications": thenS_.drugMap.drugSpecifications,
                    "detailsConsumption": thenS_.details_consumption,
                    "detailsConsumptionUnit": thenS_.details_consumption_util,
                    "drugPackagingUnit": thenS_.drug_packaging_unit,
                    "detailsUsage": thenS_.details_usage,
                    "drugPrice": thenS_.drugMap.drugPrice,
                    "drugName": thenS_.drugMap.drugName,
                    "drugId": thenS_.drugMap.id,
                    "detailsNum": details_num, // 数量
                    "storeName": thenS_.drugMap.storeName,
                    "storeId": thenS_.drugMap.storeId
                }
                console.log(StorageJosn);
                for (var i = 0; i < druglistStorage_z.length; i++) {
                    var drugid = {
                        "drug_id": druglistStorage_z[i].drugId
                    }
                    detailsList.push(drugid)
                }
            } else { //2西药
                if ($service.isUndefinedAndEmpty(thenS_.details_frequency_str)) {
                    $service.showToast('请先选择频次');
                    return;
                }
                if ($service.isUndefinedAndEmpty(thenS_.details_day)) {
                    $service.showToast('请先输入天数');
                    return;
                }
                if (thenS_.details_day > 90) {
                    $service.showToast('天数不能大于90天');
                    return;
                }
                if ($service.isUndefinedAndEmpty(thenS_.details_num)) {
                    $service.showToast('请输入数量');
                    return;
                }
                if (thenS_.details_num < 1) {
                    $service.showToast('数量不能小于1');
                    return;
                }
                if ($service.isUndefinedAndEmpty(thenS_.details_usage)) {
                    $service.showToast('请选择用法');
                    return;
                }
                for (var i = 0; i < druglistStorage_x.length; i++) { //判断缓存是否有相同的，先删除再添加
                    if (druglistStorage_x[i].drugId == thenS_.drugMap.id) {
                        druglistStorage_x.splice(i, 1)
                    }
                }
                this.setData({
                    storeId: thenS_.drugMap.storeId,
                    storeName: thenS_.drugMap.storeName,
                })
                if (thenS_.paymentMethodNum == 0) {
                    StorageJosn = {
                        "frequency_num": thenS_.frequency_num,
                        "frequency_day_num": thenS_.frequency_day_num,
                        "drugSpecifications": thenS_.drugMap.drugSpecifications,
                        "drugPackagingUnit": thenS_.drug_packaging_unit,
                        "detailsConsumption": thenS_.details_consumption,
                        "detailsConsumptionUnit": thenS_.details_consumption_util,
                        "detailsFrequencyStr": thenS_.details_frequency_str,
                        "detailsFrequencyStr2": thenS_.details_frequency_str2,
                        "detailsFrequency": thenS_.details_frequency,
                        "detailsDay": thenS_.details_day,
                        "detailsNum": thenS_.details_num,
                        "detailsUsage": thenS_.drug_type == 2 ? thenS_.details_usage : '',
                        "detailsEntrust": thenS_.detailsEntrust,
                        "drugPrice": thenS_.drugMap.drugPrice,
                        "drugName": thenS_.drugMap.drugName,
                        "drugId": thenS_.drugMap.id,
                        "storeName": thenS_.drugMap.storeName,
                        "storeId": thenS_.drugMap.storeId
                    }
                } else {
                    StorageJosn = {
                        "frequency_num": thenS_.frequency_num,
                        "drugCommonCode": thenS_.drugMap.drugCommonCode,
                        "frequency_day_num": thenS_.frequency_day_num,
                        "drugPackagingUnit": thenS_.drug_packaging_unit,
                        "drugSpecifications": thenS_.drugMap.drugSpecifications,
                        "detailsConsumption": thenS_.details_consumption,
                        "detailsConsumptionUnit": thenS_.details_consumption_util,
                        "detailsFrequencyStr": thenS_.details_frequency_str,
                        "detailsFrequencyStr2": thenS_.details_frequency_str2,
                        "detailsFrequency": thenS_.details_frequency,
                        "detailsDay": thenS_.details_day,
                        "detailsNum": thenS_.details_num,
                        "detailsUsage": thenS_.drug_type == 2 ? thenS_.details_usage : '',
                        "detailsEntrust": thenS_.detailsEntrust,
                        "drugPrice": thenS_.drugMap.drugPrice,
                        "drugName": thenS_.drugMap.drugName,
                        "drugId": thenS_.drugMap.id,
                        "storeName": thenS_.drugMap.storeName,
                        "storeId": thenS_.drugMap.storeId
                    }
                }
                console.log(StorageJosn);
                for (var i = 0; i < druglistStorage_x.length; i++) {
                    var drugid = {
                        "drug_id": druglistStorage_x[i].drugId
                    }
                    detailsList.push(drugid)
                }
            }
            this.setDurgStorage()
        } else if (index == 2) { //保存模板
            if (thenS_.drug_type == 1) { //1中药
                var detailsList = druglistStorage_z;
            } else {
                var detailsList = druglistStorage_x;
            }
            if (detailsList.length == 0) {
                $service.showToast('请先开处方');
                return;
            }
            thenS_.openPageBox_up = thenS_.openPageBox
            this.setData({
                openPageBox: 22,
                openPageBox_up: thenS_.openPageBox_up,
                bcmb_type: 0
            })
            this.getpageScrollTo()
            template_prescriptionList = { //保存模板
                detailsList: detailsList,
                prescription_price: Number(thenS_.prescription_price).toFixed(2),
                preType: 1,
            }
            this.publicUtil_getUtilTable78()
        } else if (index == 3) { //生成处方 （已开）
            // if (prescriptionListlength.length >= 5) {
            //     $service.showToast('处方不能超过5个');
            //     return;
            // }
            if (thenS_.drug_type == 1) { //1中药
                var list = druglistStorage_z;
            } else {
                var list = druglistStorage_x;
            }
            if (list.length == 0) {
                $service.showToast('请先开药品');
                return;
            }
            var storeList = []
            for (var i = 0; i < list.length; i++) {
                storeList.push(list[i].storeId)
            }
            storeList = storeList.sort()
            if ((new Set(storeList)).size == 1) {
                if (storeList[0] == 0 && this.data.hisType && !this.data.hisModal) {
                  this.setData({
                    hisModal: true
                  })
                  return
                }
                this.setData({hisModal: false})
                if (thenS_.drug_type == 1) {
                    if ($service.hospitalType == 'lianjiang' && this.data.storeData.group_no == 0) {
                      this.getDictInfo(103)
                    } else {
                      this.publicUtil_getUtilTable78()
                    }
                    this.setData({
                        prescription_isdetalis: true
                    })
                } else {
                    this.doctorSide_personal_prescription_addInquiryLogPrescription()
                }
            } else {
                wx.showToast({
                    title: '请选择同个药房的药品',
                    icon: 'none'
                })
            }
        } else if (index == 4) { //取消
            this.setData({
                prescription_isdetalis: false
            })
        } else if (index == 5) { //中药生成处方
            if ($service.isUndefinedAndEmpty(thenS_.prescription_taking)) {
                $service.showToast('请选择服用方法');
                return;
            }
            if ($service.isUndefinedAndEmpty(thenS_.prescription_num)) {
                $service.showToast('请输入付数');
                return;
            }
            this.doctorSide_personal_prescription_addInquiryLogPrescription()
        }
    },
    //把选中药品储存到缓存
    async setDurgStorage() {
        if (thenS_.drug_type == 1) { //1中药
            druglistStorage_z.push(StorageJosn)
            wx.setStorageSync("druglistStorage_z" + doctorId, $service.jsonToStr(druglistStorage_z))
        } else { //2西药
            if (druglistStorage_x.length >= 5) {
                $service.showToast('最多5个');
            } else {
                druglistStorage_x.push(StorageJosn)
            }
            console.log(druglistStorage_x)
            wx.setStorageSync("druglistStorage_x" + doctorId, $service.jsonToStr(druglistStorage_x))
        }
        this.getdruglistStorage()
        this.setData({
            sccfisshow: 0
        })
    },
    //开药（生成处方）
    async doctorSide_personal_prescription_addInquiryLogPrescription() {
        wx.showLoading({
            title: '生成中',
        })
        var this_ = this;
        // 珠海医保
        if (this.data.paymentMethodNum == 1 && this.data.hospitalType == 'zhuhai') {
            let checkList = [];
            this.data.getdruglistStoragelist.forEach((item, index) => {
                checkList.push({
                    "drugCommonCode": item.drugCommonCode,
                    "name": item.drugName,
                    "qty": item.detailsNum,
                    "splitFlag": 0
                })
            })
            console.log(checkList);
            let param = {
                "checkStockParamList": checkList
            }
            app.http.medicineListchek(param).then(res => {
                if (thenS_.drug_type == 1) { //1中药
                    var list = druglistStorage_z;
                } else {
                    var list = druglistStorage_x;
                }
                list.forEach((item, index) => {
                    item.drugPackagingUnit = item.detailsConsumptionUnit
                })
                let params = {
                    "drugs": list,
                    "id": logId,
                    "prescriptionPrice": thenS_.prescription_price,
                    "prescriptionType": thenS_.drug_type,
                    "remarks": "",
                    "storeId": thenS_.storeId,
                    // "drugPackagingUnit": thenS_.drug_packaging_unit
                    // 医保添加这个参数
                    "paymentMethod": Number(thenS_.paymentMethodNum) + 1
                }
               params.drugs[0].dosage = this.data.dosage
                if (thenS_.drug_type == 1) {
                    params.prescriptionNum = thenS_.prescription_num; //付数 中药时使用
                    params.prescriptionTaking = thenS_.prescription_taking; //服用方法 中药时使用
                    params.prescriptionRequirements = thenS_.prescription_requirements; //服用要求 中药时使用
                }
                app.http.addPrescription(params).then(res => {
                    if (thenS_.drug_type == 1) { //1中药
                        druglistStorage_z = []
                        wx.setStorageSync("druglistStorage_z" + doctorId, $service.jsonToStr(druglistStorage_z))
                    } else {
                        druglistStorage_x = []
                        wx.setStorageSync("druglistStorage_x" + doctorId, $service.jsonToStr(druglistStorage_x))
                    }
                    this.setData({
                        prescription_isdetalis: false,
                        openPageBox: 9,
                    })

                    $service.showToast(res.msg);
                    this.getpageScrollTo()
                    this.publicUtil_getInquiryLogDetails()
                }).catch(err => {
                  console.log(err)
                    $service.showToast(err.msg);
                }).finally(res => {
                    wx.hideLoading()
                })
            }).catch(err => {
                console.log(err);
                $service.showToast(err.msg);
            })
        } else {
            if (thenS_.drug_type == 1) { //1中药
                var list = druglistStorage_z;
            } else {
                var list = druglistStorage_x;
            }
            try {
              // 廉江院内处方需要校验药品数量
              if (this.data.hisType && list[0].storeId == 0) {
                let checkParams = {
                  "cardType": "",
                  "detailInfo": [],
                  "healthCardNo": "",
                  "patientName": "",
                  "patientType": 0
                }
                list.forEach(item => {
                  checkParams.detailInfo.push({
                    "detailCount": thenS_.drug_type == 1 ? item.detailsNum * thenS_.prescription_num : item.detailsNum,
                    "detailId": item.drugId,
                    "detailName": item.drugName,
                    "detailUnit": item.drugPackagingUnit
                  })
                })
                let res = await app.http.checkPrice(checkParams)
                this.setData({
                  prescription_price: res.totalPrice
                })
              }
              let params = {
                  "drugs": list,
                  "id": logId,
                  "prescriptionPrice": thenS_.prescription_price,
                  "prescriptionType": thenS_.drug_type,
                  "remarks": "",
                  // "storeId": thenS_.storeId,
                  "storeId": list[0].storeId,
                  "storeName": list[0].storeName,
                  "drugPackagingUnit": thenS_.drug_packaging_unit,
                  // 医保添加这个参数
                  "paymentMethod": Number(thenS_.paymentMethodNum) + 1
              }
              if (thenS_.drug_type == 1) {
                  params.prescriptionNum = thenS_.prescription_num; //付数 中药时使用
                  params.prescriptionTaking = thenS_.prescription_taking; //服用方法 中药时使用
                  params.prescriptionRequirements = thenS_.prescription_requirements; //服用要求 中药时使用
                  if (list[0].storeId != 0) {
                    params.prescriptionPrice = params.prescriptionPrice * thenS_.prescription_num
                  }
              }
              this.addPrescription(params) 
            } catch(err) {
              $service.showToast(err.msg)
            }
        }
    },
    // 生产处方接口
    addPrescription(params) {
      app.http.addPrescription(params).then(res => {
        if (thenS_.drug_type == 1) { //1中药
            druglistStorage_z = []
            wx.setStorageSync("druglistStorage_z" + doctorId, $service.jsonToStr(druglistStorage_z))
        } else {
            druglistStorage_x = []
            wx.setStorageSync("druglistStorage_x" + doctorId, $service.jsonToStr(druglistStorage_x))
        }
        this.setData({
            prescription_isdetalis: false,
            openPageBox: 9,
        })
        $service.showToast(res.msg);
        this.getpageScrollTo()
        this.publicUtil_getInquiryLogDetails()
      }).catch(err => {
            $service.showToast(err.msg);
      }).finally(res => {
            wx.hideLoading()
      })
    },
    //删除、编辑
    storagelist(e) {
        var index = e.currentTarget.dataset.index; //下标
        var num = e.currentTarget.dataset.num; //1编辑 2删除
        if (num == 1) {
            thenS_.sccfisshow = "1";
            var Map = thenS_.getdruglistStoragelist[index]
            if (thenS_.drug_type == 1) {
                this.setData({
                    'drugMap.drugName': Map.drugName,
                    'drugMap.id': Map.drugId || Map.id,
                    'drugMap.drugPrice': Map.drugPrice,
                    details_usage: Map.detailsUsage,
                    details_consumption_util: Map.detailsConsumptionUnit,
                    details_consumption: Map.detailsConsumption,
                    sccfisshow: thenS_.sccfisshow,
                    details_num: Map.detailsNum,
                    'drugMap.storeName': Map.storeName,
                    'drugMap.storeId': Map.storeId
                })
                if (this.data.storeData.group_no == 0 && this.data.hisType) {
                  this.getDictInfo(70)
                  this.getDictInfo(52)
                }
            } else {
                if (this.data.storeData.group_no == 0 && this.data.hisType) {
                  this.getDictInfo(51)
                  this.getDictInfo(60)
                } else {
                  this.getDrugUsageList(1)
                  this.getDrugFrequencyList()
                }
                this.setData({
                    'drugMap.drugName': Map.drugName,
                    'drugMap.id': Map.drugId || Map.id,
                    'drugMap.drugPrice': Map.drugPrice,
                    'drugMap.drugSpecifications': Map.drugSpecifications,
                    frequency_day_num: Map.frequency_day_num,
                    frequency_num: Map.frequency_num,
                    details_usage: Map.detailsUsage,
                    details_consumption_util: Map.detailsConsumptionUnit,
                    details_frequency: Map.detailsFrequency,
                    details_frequency_str: Map.detailsFrequencyStr,
                    details_frequency_str2: Map.detailsFrequencyStr,
                    details_consumption: Map.detailsConsumption,
                    details_day: Map.detailsDay,
                    details_num: Map.detailsNum,
                    detailsEntrust: Map.detailsEntrust,
                    sccfisshow: thenS_.sccfisshow,
                    'drugMap.storeName': Map.storeName,
                    'drugMap.storeId': Map.storeId
                })
                this.publicUtil_getDrugDetail2('2');
            }
            if (this.data.storeData.group_no == 0 && this.data.hisType) {
              this.getDictInfo(20)
            }
            this.getpageScrollTo()
        } else {
            if (thenS_.drug_type == 1) { //1中药
                druglistStorage_z.splice(index, 1)
                wx.setStorageSync("druglistStorage_z" + doctorId, $service.jsonToStr(druglistStorage_z))
            } else {
                druglistStorage_x.splice(index, 1)
                wx.setStorageSync("druglistStorage_x" + doctorId, $service.jsonToStr(druglistStorage_x))
            }
            this.getdruglistStorage()
        }
    },
    //返回上一页
    blck(e) {
        this.setData({
            openPageBox: 15
        })
        this.getpageScrollTo()
    },
    jisuanxiyaochufangshuliang() {
        if (this.data.details_frequency_str2) {
            this.data.list2.forEach(item => {
                if (item.frequencyPrintingName == this.data.details_frequency_str2) {
                    this.setData({
                        frequency_day_num: item.frequencyHoursNum,
                        frequency_num: item.frequencyNum
                    })
                }
            })
        }
        if (this.data.details_consumption && this.data.details_day && this.data.frequency_num && this.data.frequency_day_num && this.data.details_consumption_util) {
            console.log(medicineObj);
            if (this.data.paymentMethodNum == 0) {
                var params = {
                    "bigPackaging": medicineObj.goodsBigPacking,
                    "days": Number(this.data.details_day),
                    "dosage": this.data.details_consumption,
                    "drugSpecification": medicineObj.goodsGuige,
                    "frequencyHoursNum": this.data.frequency_day_num,
                    "frequencyNum": this.data.frequency_num,
                    "mediumPackaging": medicineObj.goodsMediumPacking,
                    "smallestPackaging": medicineObj.drugPackagingNum,
                    "usageUnit": this.data.details_consumption_util,
                    "usageUnitId": Number(medicineObj.id),
                    "drugVolumeUnit": medicineObj.drugVolumeUnit,
                    "drugSmallestUnit": medicineObj.drugSmallestUnit,
                    "drugUnit": medicineObj.drugUnit
                }
            } else {
                var params = {
                    "bigPackaging": medicineObj.goodsBigPacking,
                    "days": Number(this.data.details_day),
                    "dosage": this.data.details_consumption,
                    "drugSpecification": medicineObj.norms,
                    "frequencyHoursNum": this.data.frequency_day_num,
                    "frequencyNum": this.data.frequency_num,
                    "mediumPackaging": medicineObj.goodsMediumPacking,
                    "smallestPackaging": medicineObj.drugPackagingNum,
                    "usageUnit": this.data.details_consumption_util,
                    "usageUnitId": Number(medicineObj.id),
                    "drugVolumeUnit": medicineObj.drugVolumeUnit,
                    "drugSmallestUnit": medicineObj.unit,
                    "drugUnit": medicineObj.drugUnit
                }
            }
            app.http.getTheCalculationFormula(params).then(res => {
                this.setData({
                    details_num: res.data.quantityOfMedication
                })
            })
        }
    },


    // ---------- 检验检查
    //已生成检验检查单
    publicUtil_getInquiryLogChecklistDetails_back(jsonBack) {
        var data = $service.strToJson(jsonBack.data).data;
        var checklistMap = data.checklistMap; //检验信息
        var checklistDetailsList = checklistMap.checklistDetailsList; //检验列表
        for (var i = 0; i < checklistDetailsList.length; i++) {
            if (checklistDetailsList[i].checklist_type == 1) {
                thenS_.opinionList.push(checklistDetailsList[i]);
            }
            if (checklistDetailsList[i].checklist_type != 1) {
                thenS_.opinionList2.push(checklistDetailsList[i]);
            }
        }
        this.setData({
            opinionList: thenS_.opinionList,
            opinionList2: thenS_.opinionList2,
            lof_proposal: checklistMap.treatment_suggestion
        })
    },
    //一级数据
    doctorSide_personal_inquiry_getUtilChecklistClass: function () {
        app.http.getChecklistClassName().then(res => {
            var checklistClassList = res.data.list; //大分类
            for (var i = 0; i < checklistClassList.length; i++) {
                checklistClassList[i].isshow = false;
            }
            this.setData({
                checklistClassList: checklistClassList
            })
        })
    },
    // 二级数据
    clickChecklistClass() {
        app.http.clickChecklistClass({
            id: thenS_.dataId
        }).then(res => {
            var nextClassList = res.data.list;
            for (var i = 0; i < nextClassList.length; i++) {
                nextClassList[i].istwoshow = false;
            }
            console.log(res.data.list)
            this.setData({
                nextClassList: nextClassList,
            })
        }).catch(err => {
            $service.showToast(err.msg)
        })
    },
    //列表点击事件
    checklistClasstap(e) {
        var index = e.currentTarget.dataset.index;
        var num = e.currentTarget.dataset.num;
        if (num == 1) { //1级列表点击
            dataId = thenS_.checklistClassList[index].id;
            for (var i = 0; i < thenS_.checklistClassList.length; i++) {
                if (thenS_.checklistClassList[i].id == dataId) {
                    thenS_.checklistClassList[i].isshow = !thenS_.checklistClassList[i].isshow;
                } else {
                    thenS_.checklistClassList[i].isshow = false;
                }
            }
            this.setData({
                dataId: dataId,
                checklistClassList: thenS_.checklistClassList,
                nextClassList: [],
                checklistList: []
            })
            this.clickChecklistClass();
            // this.doctorSide_personal_inquiry_getUtilChecklistClass()
        } else if (num == 2) { //二级列表点击
            console.log(thenS_.nextClassList[index])
            if (!thenS_.nextClassList[index].checklistClassResult) {
                thenS_.checklistList = thenS_.nextClassList[index].checklistResult
                thenS_.isThree = false;
            } else {
                let dataList = thenS_.nextClassList[index].checklistClassResult;
                for (var i = 0; i < dataList.length; i++) {
                    dataList[i].isthreeshow = false;
                }
                thenS_.checklistList = dataList
                thenS_.isThree = true;
            }
            let id = thenS_.nextClassList[index].id;
            for (var i = 0; i < thenS_.nextClassList.length; i++) {
                if (thenS_.nextClassList[i].id == id) {
                    thenS_.nextClassList[i].istwoshow = !thenS_.nextClassList[i].istwoshow;
                } else {
                    thenS_.nextClassList[i].istwoshow = false;
                }
            }
            this.setData({
                isThree: thenS_.isThree,
                nextClassList: thenS_.nextClassList,
                checklistList: thenS_.checklistList
            })
            console.log(thenS_.checklistList)
            // this.doctorSide_personal_inquiry_getUtilChecklistClass()
        } else if (num == 3) { //三级列表点击
            console.log(thenS_.checklistList[index])
            let id = thenS_.checklistList[index].id;
            for (var i = 0; i < thenS_.checklistList.length; i++) {
                if (thenS_.checklistList[i].id == id) {
                    thenS_.checklistList[i].isthreeshow = !thenS_.checklistList[i].isthreeshow;
                } else {
                    thenS_.checklistList[i].isthreeshow = false;
                }
            }
            this.setData({
                checklistList: thenS_.checklistList,
                checkThreeList: thenS_.checklistList[index].checklistResult
            })
            console.log(thenS_.checklistList[index].checklistResult)
        }

    },
    //添加至检验检查项目
    addOpinion(e) {
        if ($service.isUndefinedAndEmpty(thenS_.inquiryMap.mainSuit)) {
            $service.showToast("请先输入主诉")
            return;
        }
        if ($service.isUndefinedAndEmpty(thenS_.inquiryMap.diagnosis)) {
            $service.showToast("请先输入诊断")
            return;
        }
        var index = e.currentTarget.dataset.index;
        var num = e.currentTarget.dataset.num;
        var type = e.currentTarget.dataset.type;
        if (num == 1) { //检验检查
            if (type == 1) {
                console.log(thenS_.checklistList[index])
                if (thenS_.opinionList.length > 4) {
                    $service.showToast('最多五个');
                    return;
                }
                for (var i = 0; i < thenS_.opinionList.length; i++) {
                    if (thenS_.checklistList[index].id == thenS_.opinionList[i].id) {
                        $service.showToast('请不要重复添加');
                        return;
                    }
                }
                $service.showToast('添加成功')
                thenS_.opinionList.push(thenS_.checklistList[index])
            } else {
                // if(thenS_.opinionList2.length > 4){
                //     $service.showToast('最多五个');
                //     return;
                // }
                // for(var i = 0; i < thenS_.opinionList2.length;i++){
                //     if(thenS_.checklistList[index].id == thenS_.opinionList2[i].id){
                //         $service.showToast('请不要重复添加');
                //         return;
                //     }
                // }
                // thenS_.opinionList2.push(thenS_.checklistList[index])
            }
        } else if (num == 2) { //新增申请单
            var i = e.currentTarget.dataset.i;
            var checklistList = thenS_.checklistList[index];
            var checklist_class_id = thenS_.checklistClassList[i].id;
            var objMap = {
                inquiryMap: thenS_.inquiryMap,
                checklistList: checklistList,
                checklist_class_id: checklist_class_id,
                checklistListAll: checklistListAll
            }
            thenS_.jyjcXdb_opinionList[0] = objMap.checklistList
            wx.setStorageSync('checklistListAll' + logId, "1")
            this.setData({
                checklist_objMap: objMap,
                jyjcXdb_opinionList: thenS_.jyjcXdb_opinionList
            })
            if (type == '模板一') {
                thenS_.openPageBox = 17
            } else {
                // this.doctorSide_personal_inquiry_getUtilChecklistClass2()
                thenS_.openPageBox = 18
            }

        }
        this.setData({
            opinionList: thenS_.opinionList,
            // opinionList2 :thenS_.opinionList2,
            openPageBox: thenS_.openPageBox
        })
        this.getpageScrollTo()
    },
    //删除检验项目
    delopinionList(e) {
        var index = e.currentTarget.dataset.index;
        var num = e.currentTarget.dataset.num;
        let type = e.currentTarget.dataset.type
        if (num == 1) {
            $service.showToast("删除成功")
            thenS_.opinionList.splice(index, 1)
        } else if (num == 2) {
            app.http.deleteInspectionOpinion({
                id: thenS_.opinionList2[index].id
            }).then(res => {
                $service.showToast('删除成功')
                thenS_.opinionList2.splice(index, 1)
                this.publicUtil_getInquiryLogDetails()
            }).catch(err => {
                $service.showToast(err.msg)
            })
        } else {
            if (type == 'inquiry_checklist_ECG_template') { // 删除心电图申请单
                app.http.deleteCommonApplicationForm({
                    id: thenS_.opinionList3[index].id
                }).then(res => {
                    $service.showToast('删除成功')
                    thenS_.opinionList3.splice(index, 1);
                }).catch(err => {
                    $service.showToast(err.msg)
                })
            } else { // 删除普通申请单
                app.http.deleteECGApplicationForm({
                    id: thenS_.opinionList3[index].id
                }).then(res => {
                    $service.showToast('删除成功')
                    thenS_.opinionList3.splice(index, 1);
                }).catch(err => {
                    $service.showToast(err.msg)
                })
            }
            this.setData({
                opinionList3: thenS_.opinionList3
            })
            this.publicUtil_getInquiryLogDetails()
        }
        this.setData({
            opinionList: thenS_.opinionList,
            opinionList2: thenS_.opinionList2,
            opinionList3: thenS_.opinionList3,
            'inquiryMap.commonFormListResult': thenS_.inquiryMap.commonFormListResult
        })
    },
    //保存
    addInspectionBox() {
        if ($service.isUndefinedAndEmpty(thenS_.inquiryMap.mainSuit)) {
            $service.showToast("请先输入主诉")
            return;
        }
        if ($service.isUndefinedAndEmpty(thenS_.inquiryMap.diagnosis)) {
            $service.showToast("请先输入诊断")
            return;
        }

        var detailsList = thenS_.opinionList;
        if (detailsList.length == 0) {
            $service.showToast("请添加检验检查意见！")
            return;
        }
        if (!$service.isUndefinedAndEmpty(thenS_.lof_proposal)) {
            if (detailsList.length == 0) {
                $service.showToast("有填写医生建议，就必须添加检验检查意见！")
                return;
            }
        }
        if (detailsList.length != 0) {
            if ($service.isUndefinedAndEmpty(thenS_.lof_proposal)) {
                $service.showToast("请填写医生建议")
                return;
            }
        }
        wx.showLoading({
            title: '生成中',
        })
        let checkId = detailsList.map(item => item.id).join();
        let checkProject = detailsList.map(item => item.checklistClassName).join();
        let params = {
            checkId,
            checkProject,
            logId: logId,
            processingOpinion: thenS_.lof_proposal
        }
        app.http.addInspectionOpinion(params).then(res => {
            wx.showToast({
                "title": '保存成功',
                "icon": "none",
                duration: 4000
            });
            this.publicUtil_getInquiryLogDetails()
            this.setData({
                opinionList: [],
                lof_proposal: ''
            })
        }).catch(err => {
            $service.showToast(err.msg);
        }).finally(() => {
            wx.hideLoading();
        })
    },
    //监听输入框
    jyjcinputChange(e) {
        thenS_.lof_proposal = e.detail.value
        this.setData({
            lof_proposal: thenS_.lof_proposal
        })
    },

    // -------------- 检验检查心电图
    //监听输入框
    jyjcSqdinputChange(e) {
        var index = e.currentTarget.dataset.index;
        if (index == 1) { //上次单号
            thenS_.checklist_last_code = e.detail.value
        } else if (index == 2) { //摘要
            thenS_.checklist_abstract = e.detail.value
        } else if (index == 3) { //收缩压
            thenS_.checklist_sbp = e.detail.value
        } else if (index == 4) { //舒张压
            thenS_.checklist_dbp = e.detail.value
        } else if (index == 5) { //备注
            thenS_.bz = e.detail.value
        } else if (index == 6) { //使用洋地黄开始时间 年
            thenS_.beforeYear = e.detail.value
        } else if (index == 7) { //使用洋地黄开始时间 月
            thenS_.beforeMon = e.detail.value
        } else if (index == 8) { //使用洋地黄开始时间 日
            thenS_.beforeDay = e.detail.value
        } else if (index == 9) { //有关药物开始时间 年
            thenS_.newYear = e.detail.value
        } else if (index == 10) { //有关药物开始时间 月
            thenS_.newMon = e.detail.value
        } else if (index == 11) { //有关药物开始时间 日
            thenS_.newDay = e.detail.value
        } else if (index == 12) { //使用洋地黄用量
            thenS_.checklist_digitalization_num = e.detail.value
        } else if (index == 13) { //有关药物名称
            thenS_.checklist_other_drugs_name = e.detail.value
        } else if (index == 14) { //有关药物开始时间 年
            thenS_.beforeYear2 = e.detail.value
        } else if (index == 15) { //有关药物开始时间 月
            thenS_.beforeMon2 = e.detail.value
        } else if (index == 16) { //有关药物开始时间 日
            thenS_.beforeDay2 = e.detail.value
        } else if (index == 17) { //有关药物开始时间 年
            thenS_.newYear2 = e.detail.value
        } else if (index == 18) { //有关药物开始时间 月
            thenS_.newMon2 = e.detail.value
        } else if (index == 19) { //有关药物开始时间 日
            thenS_.newDay2 = e.detail.value
        } else if (index == 20) { //有关药物用量
            thenS_.checklist_other_drugs_num = e.detail.value
        }
        this.setData({
            checklist_last_code: thenS_.checklist_last_code, //上次单号
            checklist_abstract: thenS_.checklist_abstract, //摘要
            checklist_sbp: thenS_.checklist_sbp, //收缩压
            checklist_dbp: thenS_.checklist_dbp, //舒张压
            checklist_digitalization_num: thenS_.checklist_digitalization_num, //使用洋地黄用量
            checklist_other_drugs_name: thenS_.checklist_other_drugs_name, //有关药物名称
            checklist_other_drugs_num: thenS_.checklist_other_drugs_num, //有关药物用量
            checklist_inspection_result: thenS_.checklist_inspection_result, //有关检验结果
            beforeYear: thenS_.beforeYear, //使用洋地黄开始时间 年
            beforeMon: thenS_.beforeMon, //使用洋地黄开始时间 月
            beforeDay: thenS_.beforeDay, //使用洋地黄开始时间 日
            beforeYear2: thenS_.beforeYear2, //有关药物开始时间 年
            beforeMon2: thenS_.beforeMon2, //有关药物开始时间 月
            beforeDay2: thenS_.beforeDay2, //有关药物开始时间 日
            newYear: thenS_.newYear, //使用洋地黄结束时间 年
            newMon: thenS_.newMon, //使用洋地黄结束时间 月
            newDay: thenS_.newDay, //使用洋地黄结束时间 日
            newYear2: thenS_.newYear2, //有关药物结束时间 年
            newMon2: thenS_.newMon2, //有关药物结束时间 月
            newDay2: thenS_.newDay2, //有关药物结束时间 日
            bz: thenS_.bz //备注
        })
    },
    choosetap(e) {
        var index = e.currentTarget.dataset.index;
        var num = e.currentTarget.dataset.num;
        if (num == 1) {
            thenS_.is_digitalization = index
        } else if (num == 2) {
            thenS_.is_other_drugs = index
        }
        this.setData({
            is_digitalization: thenS_.is_digitalization,
            is_other_drugs: thenS_.is_other_drugs
        })
    },
    //保存、
    addchecklist() {
        var this_ = this
        if (!$service.isUndefinedAndEmpty(this.data.checklist_sbp)) {
            if (this.data.checklist_dbp == '') {
                $service.showToast('有填写收缩压就必须填写舒张压');
                return;
            }
        }
        if (!$service.isUndefinedAndEmpty(this.data.checklist_dbp)) {
            if (this.data.checklist_sbp == '') {
                $service.showToast('有填写舒张压就必须填写收缩压');
                return;
            }
        }
        if (Number(this.data.checklist_sbp) < Number(this.data.checklist_dbp)) {
            $service.showToast('收缩压必须大于舒张压');
            return;
        }
        if (thenS_.is_other_drugs == 1 && $service.isUndefinedAndEmpty(thenS_.checklist_other_drugs_name)) {
            $service.showToast('请填写药物');
            return;
        }
        if (thenS_.is_digitalization == 1) {
            var checklist_digitalization_start = thenS_.beforeYear + '-' + thenS_.beforeMon + '-' + thenS_.beforeDay
            var checklist_digitalization_end = thenS_.newYear + '-' + thenS_.newMon + '-' + thenS_.newDay
        } else {
            var checklist_digitalization_start = ''
            var checklist_digitalization_end = ''
        }
        if (thenS_.is_other_drugs == 1) {
            var checklist_other_drugs_start = thenS_.beforeYear2 + '-' + thenS_.beforeMon2 + '-' + thenS_.beforeDay2
            var checklist_other_drugs_end = thenS_.newYear2 + '-' + thenS_.newMon2 + '-' + thenS_.newDay2
        } else {
            var checklist_other_drugs_start = ''
            var checklist_other_drugs_end = ''
        }
        let params = {
            "checkId": thenS_.checklist_objMap.checklistList.id, //项目id
            "checkProject": thenS_.checklist_objMap.checklistList.checklistClassName, // 检查项目	
            "checklistAbstract": thenS_.checklist_abstract, //病历及检查摘要	
            "checklistDbp": thenS_.checklist_dbp, // 舒张压
            "checklistDigitalizationEnd": checklist_digitalization_end, // 使用洋地黄结束时间	
            "checklistDigitalizationNum": thenS_.checklist_digitalization_num, // 使用洋地黄用量	
            "checklistDigitalizationStart": checklist_digitalization_start, // 使用洋地黄开始时间	
            "checklistLastCode": thenS_.checklist_last_code, // 上次心电图单号	
            "checklistOtherDrugsEnd": checklist_other_drugs_start, //有关药物结束时间
            "checklistOtherDrugsName": thenS_.checklist_other_drugs_name, // 有关药物名称	
            "checklistOtherDrugsNum": thenS_.checklist_other_drugs_num, // 有关药物用量	
            "checklistOtherDrugsStart": checklist_other_drugs_start, // 有关药物开始时间	
            "checklistSbp": thenS_.checklist_sbp, // 收缩压
            "isDigitalization": thenS_.is_digitalization, // 是否使用过洋地黄 0否 1是
            "isOtherDrugs": thenS_.is_other_drugs, // 是否使用有关药物 0否 1是
            "logId": logId, // 问诊记录主键
            "remarks": thenS_.bz // 备注
        }
        wx.showLoading({
            title: '生成中',
        })
        app.http.addCommonApplication(params).then(res => {
            wx.showToast({
                "title": '保存成功',
                "icon": "none",
                duration: 4000
            });
            this_.publicUtil_getInquiryLogDetails()
            this_.setData({
                openPageBox: 2
            })
        }).then(err => {
            $service.showToast(err.msg)
        }).finally(() => {
            wx.hideLoading()
        })
    },
    //日期时间计算
    getBeforeDate(n, num) {
        var n = n;
        var d = new Date();
        var year = d.getFullYear();
        var mon = d.getMonth() + 1;
        var day = d.getDate();
        if (day <= n) {
            if (mon > 1) {
                mon = mon - 1;
            } else {
                year = year - 1;
                mon = 12;
            }
        }
        d.setDate(d.getDate() - n);
        year = d.getFullYear();
        mon = d.getMonth() + 1;
        mon = mon < 10 ? ('0' + mon) : mon
        day = d.getDate();
        day = day < 10 ? ('0' + day) : day,
            this.setData({
                beforeYear: year,
                beforeMon: mon,
                beforeDay: day
            })

    },



    jyjcXdb_tapisshow(e) {
        this.data.jyjcXdbisshow = !this.data.jyjcXdbisshow
        this.setData({
            jyjcXdbisshow: this.data.jyjcXdbisshow
        })
    },
    //列表点击事件
    jyjcXdb_checklistClasstap(e) {
        console.log(e)
        var index = e.currentTarget.dataset.index;
        var num = e.currentTarget.dataset.num;
        thenS_.jyjcXdb_dataId2 = thenS_.jyjcXdb_nextClassList[index].checklist_class_id;
        thenS_.checklist_objMap.checklist_class_id = thenS_.jyjcXdb_dataId2;
        for (var i = 0; i < thenS_.jyjcXdb_nextClassList.length; i++) {
            if (thenS_.jyjcXdb_nextClassList[i].checklist_class_id == thenS_.jyjcXdb_dataId2) {
                thenS_.jyjcXdb_nextClassList[i].istwoshow = !thenS_.jyjcXdb_nextClassList[i].istwoshow;
            } else {
                thenS_.jyjcXdb_nextClassList[i].istwoshow = false;
            }

        }
        this.setData({
            jyjcXdb_dataId2: thenS_.jyjcXdb_dataId2,
            jyjcXdb_nextClassList: thenS_.jyjcXdb_nextClassList,
            jyjcXdb_checklistList: [],
            checklist_objMap: thenS_.checklist_objMap
        })
        // this.doctorSide_personal_inquiry_getUtilChecklistClass2()
    },
    //添加至检验检查项目
    jyjcXdb_addOpinion(e) {
        console.log(e)
        var index = e.currentTarget.dataset.index;
        var num = e.currentTarget.dataset.num;
        var type = e.currentTarget.dataset.type;
        if (num == 1) { //检验检查
            if (thenS_.jyjcXdb_opinionList.length > 4) {
                $service.showToast('最多五个');
                return;
            }
            for (var i = 0; i < thenS_.jyjcXdb_opinionList.length; i++) {
                if (thenS_.jyjcXdb_checklistList[index].checklist_id == thenS_.jyjcXdb_opinionList[i].checklist_id) {
                    $service.showToast('请不要重复添加');
                    return;
                }
            }
            thenS_.jyjcXdb_opinionList.push(thenS_.jyjcXdb_checklistList[index])
        }
        this.setData({
            jyjcXdb_opinionList: thenS_.jyjcXdb_opinionList
        })
    },
    //删除检验项目
    jyjcXdb_delopinionList(e) {
        if (thenS_.jyjcXdb_opinionList.length > 1) {
            var index = e.currentTarget.dataset.index;
            var num = e.currentTarget.dataset.num;
            thenS_.jyjcXdb_opinionList.splice(index, 1)
            this.setData({
                jyjcXdb_opinionList: thenS_.jyjcXdb_opinionList
            })
        } else {
            $service.showToast('至少保留一个');
            return
        }

    },
    //保存、
    jyjcXdb_addchecklist() {
        var this_ = this
        let params = {
            "checkId": thenS_.jyjcXdb_opinionList[0].id, // 检查项目id
            "checkProject": thenS_.jyjcXdb_opinionList[0].checklistClassName, // 检查项目	
            "checkResult": thenS_.jyjcXdb_checklist_inspection_result, // 检验结果	
            "checklistAbstract": thenS_.jyjcXdb_checklist_abstract, // 病历及检查摘要	
            "logId": logId, // 问诊记录主键	
            "remarks": thenS_.jyjcXdb_bz
        }
        wx.showLoading({
            title: '生成中',
        })
        app.http.addECGApplication(params).then(res => {
            wx.showToast({
                "title": '保存成功',
                "icon": "none",
                duration: 3000
            });
            this_.publicUtil_getInquiryLogDetails()
            this_.setData({
                openPageBox: 2
            })
        }).catch(err => {
            $service.showToast(err.msg);
        }).finally(() => {
            wx.hideLoading()
        })
    },
    //监听输入框
    jyjcXdb_inputChange(e) {
        var index = e.currentTarget.dataset.index;
        if (index == 1) { //摘要
            thenS_.jyjcXdb_checklist_abstract = e.detail.value
        } else if (index == 2) {
            thenS_.jyjcXdb_checklist_inspection_result = e.detail.value
        } else if (index == 3) {
            thenS_.jyjcXdb_bz = e.detail.value
        }
        this.setData({
            jyjcXdb_checklist_abstract: thenS_.jyjcXdb_checklist_abstract,
            jyjcXdb_checklist_inspection_result: thenS_.jyjcXdb_checklist_inspection_result,
            jyjcXdb_bz: thenS_.jyjcXdb_bz
        })
    },

    // ---------------- 健康指导
    // 健康指导
    getHealthGuidanceModelList: function () {
        let type = 0;
        if (this.data.health_active) {
            type = 0;
        } else {
            type = 1;
        }
        let params = {
            "guidanceName": this.data.guidance_name,
            "modelType": type
        }
        app.http.getHealthGuidanceModelList(params).then(res => {
            this.setData({
                carouselActivityList: res.data.list
            })
        }).catch(err => {
            $service.showToast(err.msg)
        })
    },
    tabclick(e) { //方法
        console.log(e)
        var index = e.currentTarget.dataset.index;
        if (index == 0) {
            this.data.health_active = true
        } else {
            this.data.health_active = false
        }
        this.setData({
            health_active: this.data.health_active
        })
        this.getHealthGuidanceModelList()
    },

    watchmodel(e) { //输入框监听
        this.setData({
            guidance_name: e.detail.value
        })
        this.getHealthGuidanceModelList()
    },
    async gotopage(e) { //1删除模板 2查看模板 3引用意见单 4关闭弹窗 5填写意见单
        var this_ = this
        var index = e.currentTarget.dataset.index;
        var num = e.currentTarget.dataset.num;
        if (index == 1) {
            wx.showModal({
                title: '温馨提示',
                content: '确定要删除此模版？',
                success(res) {
                    if (res.confirm) {
                        let id = this_.data.carouselActivityList[num].id;
                        app.http.delHealthGuidanceModel({
                            id: id
                        }).then(res => {
                            $service.showToast('删除成功')
                            this_.getHealthGuidanceModelList()
                        }).catch(err => {
                            $service.showToast(err.msg)
                        })
                    }
                }
            })
        } else if (index == 2) {
            let id = this_.data.carouselActivityList[num].id;
            let data = await this.getHealthGuidanceModelDetail(id);
            this.setData({
                health_isdetalis: true,
                guidance_nameText: data.guidanceContent
            })
        } else if (index == 3) {
            thenS_.openPageBox_up = thenS_.openPageBox
            let id = this_.data.carouselActivityList[num].id;
            let data = await this.getHealthGuidanceModelDetail(id);
            this.setData({
                openPageBox: 19,
                guidance_content: data.guidanceContent,
                openPageBox_up: thenS_.openPageBox_up
            })
            this.getpageScrollTo()
        } else if (index == 4) {
            this.setData({
                health_isdetalis: false
            })
        } else if (index == 5) {
            thenS_.openPageBox_up = thenS_.openPageBox
            this.setData({
                openPageBox: 19,
                guidance_content: '',
                openPageBox_up: thenS_.openPageBox_up
            })
            this.getpageScrollTo()
        }
    },
    // 获取健康指导模板详情
    getHealthGuidanceModelDetail(id) {
        return app.http.getHealthGuidanceModelDetail({
            id: id
        }).then(res => {
            return res.data
        }).catch(err => {
            $service.showToast(err.msg);
        })
    },
    // 获取健康指导意见单详情
    viewInquiryLogHealthGuidance(id) {
        return app.http.viewInquiryLogHealthGuidance({
            id: id
        }).then(res => {
            return res.data
        }).catch(err => {
            $service.showToast(err.msg);
        })
    },
    //填写健康指导意见单
    addHealthGuidance: function () {
        if ($service.isUndefinedAndEmpty(thenS_.inquiryMap.mainSuit)) {
            $service.showToast("请先输入主诉")
            return;
        }
        if ($service.isUndefinedAndEmpty(thenS_.inquiryMap.diagnosis)) {
            $service.showToast("请先输入诊断")
            return;
        }
        if ($service.isUndefinedAndEmpty(thenS_.guidance_content)) {
            $service.showToast('请输入指导内容');
            return;
        }
        if (thenS_.guidanceList.length > 5) {
            $service.showToast('意见指导最多5条');
            return;
        }
        wx.showLoading({
            title: '生成中',
        })
        let params = {
            "guidanceContent": thenS_.guidance_content,
            "logId": logId
        }
        app.http.addInquiryLogHealthGuidance(params).then(res => {
            this.setData({
                guidance_content: '',
                selected: 2
            })
            this.publicUtil_getInquiryLogDetails()
        }).catch(err => {
            $service.showToast(err.msg)
        }).finally(res => {
            wx.hideLoading()
        })
    },
    drop_down(e) { //
        console.log(e)
        this.setData({
            hiddenName: !this.data.hiddenName
        })
    },
    pop: function () { //弹窗
        this.setData({
            showModal: true
        })
    },
    // 禁止屏幕滚动
    ms: function () {},
    // 弹出层里面的弹窗
    ok: function () {
        this.setData({
            showModal: false
        })
    },
    selected: function (e) {
        var index = e.currentTarget.dataset.index;
        this.setData({
            selected: index
        })
    },
    jkzdxqtx_inputChange(e) { //输入框监听
        var index = e.currentTarget.dataset.index;
        if (index == 1) {
            thenS_.guidance_content = e.detail.value
        }
        this.setData({
            guidance_content: thenS_.guidance_content
        })
    },
    async jkzdxqtx_gotopage(e) { //1删除模板 2查看模板 3引用意见单 4关闭弹窗
        var this_ = this
        var index = e.currentTarget.dataset.index;
        var num = e.currentTarget.dataset.num;
        if (index == 1) {
            wx.showModal({
                title: '温馨提示',
                content: '确定要作废此意见单？',
                success(res) {
                    if (res.confirm) {
                        let id = this_.data.guidanceList[num].id;
                        app.http.deleteInquiryLogHealthGuidance({
                            id: id
                        }).then(res => {
                            $service.showToast(res.msg);
                            this_.publicUtil_getInquiryLogDetails()
                        }).catch(err => {
                            $service.showToast(err.msg);
                        })
                    }
                }
            })
        } else if (index == 2) {
            let data = await this.viewInquiryLogHealthGuidance(this_.data.guidanceList[num].id);
            this.setData({
                jkzdxqtx_isdetalis: true,
                jkzdxqtx_guidance_nameText: data.guidanceContent
            })
        } else if (index == 3) {
            let data = await this.viewInquiryLogHealthGuidance(this_.data.guidanceList[num].id);
            thenS_.openPageBox_up = thenS_.openPageBox
            this.setData({
                openPageBox: 22,
                bcmb_type: 1,
                openPageBox_up: thenS_.openPageBox_up
            })
            template_prescriptionList = {
                guidance_content: data.guidanceContent,
                type: 1
            }
            this.getpageScrollTo()
        } else if (index == 4) {
            this.setData({
                jkzdxqtx_isdetalis: false
            })
        } else if (index == 5) {
            thenS_.openPageBox_up = thenS_.openPageBox
            this.setData({
                openPageBox: 22,
                bcmb_type: 1,
                openPageBox_up: thenS_.openPageBox_up
            })
            template_prescriptionList = {
                guidance_content: this_.data.guidance_content,
                type: 1
            }
            this.getpageScrollTo()
            this.publicUtil_getUtilTable78()
        }

    },



    // ---------------- 住院建议生成
    //监听input框
    zyjys_inputChange(e) {
        var index = e.currentTarget.dataset.index;
        if (index == 1) {
            thenS_.doctorMap.departmentName = e.detail.value
        } else {
            thenS_.zyjys_bz = e.detail.value
            $service.setStore('zyjys_bz', thenS_.zyjys_bz)
        }
        this.setData({
            'doctorMap.departmentName': thenS_.doctorMap.departmentName,
            bz: thenS_.zyjys_bz
        })
    },
    //生成住院建议书
    qr_btn() {
        if ($service.isUndefinedAndEmpty(thenS_.inquiryMap.mainSuit)) {
            $service.showToast("请先输入主诉")
            return;
        }
        if ($service.isUndefinedAndEmpty(thenS_.inquiryMap.diagnosis)) {
            $service.showToast("请先输入诊断")
            return;
        }
        if ($service.isUndefinedAndEmpty(thenS_.doctorMap.departmentName)) {
            $service.showToast('请输入科室')
            return
        }
        wx.showLoading({
            title: '生成中',
        })
        let params = {
            "hospitalizationDepartment": thenS_.doctorMap.departmentName,
            "hospitalizationHospital": thenS_.inquiryMap.hospitalName,
            "logId": logId,
            "remark": thenS_.zyjys_bz
        }
        app.http.addInquiryLogHospitalization(params).then(res => {
            $service.showToast('生成成功');
            this.publicUtil_getInquiryLogDetails()
            setTimeout(() => {
                this.closeBox('', 1)
            }, 500)
        }).catch(err => {
            $service.showToast(err.msg)
        }).finally(res => {
            wx.hideLoading()
        })
    },

    // ---------------- 问诊规范

    //问诊规范
    //数据
    async doctorSide_personal_inquiry_getSpecification() {
        let list = null;
        let params = {
            "current": page,
            "size": 10
        }
        if (thenS_.wzgf_active === '1') {
            params.modelName = thenS_.wzgf_queryName
            await app.http.getDoctorNormalConsultationList(params).then(res => {
                list = res.data.list
            })
        } else if (thenS_.wzgf_active === '2') {
            params.keyword = thenS_.wzgf_queryName
            await app.http.getDrugSpeciFicationList(params).then(res => {
                list = res.data.list
            })
        } else {
            params.diagnosisName = thenS_.wzgf_queryName
            await app.http.getDiagnosisSpeciFicationList(params).then(res => {
                list = res.data.list
            })
        }
        if (page == 1) {
            thenS_.loadingText = '';
            if (thenS_.wzgf_active == 1) {
                thenS_.wzgf_list = list
            } else if (thenS_.wzgf_active == 2) {
                thenS_.wzgf_list2 = list
            } else {
                thenS_.wzgf_list3 = list
            }
        } else {
            if (list.length <= 0) {
                thenS_.loadingType = false;
                thenS_.loadingText = '没有更多了';
            } else {
                for (var i = 0; i < list.length; i++) {
                    if (thenS_.wzgf_active == 1) {
                        thenS_.wzgf_list.push(list[i])
                    } else if (thenS_.wzgf_active == 2) {
                        thenS_.wzgf_list2.push(list[i])
                    } else {
                        thenS_.wzgf_list3.push(list[i])
                    }
                    thenS_.loadingText = '加载更多';
                }
            }
        }
        this.setData({
            wzgf_list: thenS_.wzgf_list,
            wzgf_list2: thenS_.wzgf_list2,
            wzgf_list3: thenS_.wzgf_list3,
            loadingText: thenS_.loadingText,
            loadingType: thenS_.loadingType
        })
    },
    wzgf_tapactive(e) {
        console.log(e)
        var index = e.currentTarget.dataset.index;
        this.setData({
            wzgf_active: index,
            loadingText: '加载更多',
            loadingType: true
        })
        page = 1
        this.getalldo()
    },
    //监听input框
    wzgf_inputChange(e) {
        console.log(e)
        var index = e.currentTarget.dataset.index;
        if (index == 1) {
            thenS_.wzgf_queryName = e.detail.value
        }
        this.setData({
            wzgf_queryName: thenS_.wzgf_queryName
        })
        page = 1
        this.getalldo()
    },
    // 药品规范弹窗
    wzgf_openPage(e) {
        var index = e.currentTarget.dataset.index;
        var num = e.currentTarget.dataset.num;
        if (num == 1) {
            var params = {
                "id": this.data.wzgf_list2[index].id
            }
            app.http.viewDrugSpeciFication(params).then(res => {
                console.log(res)
                this.setData({
                    wzgf_isdetalis: true,
                    wzgf_drugMap: res.data,
                    incompatibilityList: res.data.utilIncompatibilityListByIdResult
                })
            }).catch(err => {
                $service.showToast(err.msg)
            })
        } else if (num == 2) {
            app.http.getDrugSpeciFicationDetail({
                id: this.data.wzgf_list2[index].id
            }).then(res => {
                console.log(res)
                thenS_.openPageBox_up = thenS_.openPageBox
                this.setData({
                    ypxx_drugMap: res.data,
                    openPageBox: 21,
                    openPageBox_up: thenS_.openPageBox_up
                })
                this.getpageScrollTo()
            }).catch(err => {
                $service.showToast(err.msg)
            })
        } else if (num == 3) {
            this.setData({
                wzgf_isdetalis: false
            })
        }
    },


    // ---------------- 填写诊断、主诉、过敏史等
    // 药物过敏史 保存接口
    updateAllergyHistory() {
        let params = {
            "id": inquiryPatientId,
            "patientAllergyDetails": thenS_.txdiagnosis_iinquiry_patient_allergy_details
        }
        app.http.updateAllergyHistory(params).then(res => {
            $service.showToast(res.msg);
            this.setData({
                'inquiryMap.patientAllergyDetails': thenS_.txdiagnosis_iinquiry_patient_allergy_details
            })
            this.publicUtil_getInquiryLogDetails();
        }).catch(err => {
            $service.showToast(err.msg);
        })
    },
    // 主诉 现病史 既往史 保存 接口
    updateInquiryLog() {
        let params = {
            "historyPresentIllness": thenS_.txdiagnosis_log_history_present_illness,
            "id": logId,
            "mainSuit": thenS_.txdiagnosis_log_main_suit,
            "presentIllness": thenS_.txdiagnosis_log_present_illness
        }
        app.http.updateInquiryLog(params).then(res => {
            $service.showToast(res.msg);
            this.setData({
                'inquiryMap.historyPresentIllness': thenS_.txdiagnosis_log_history_present_illness,
                'inquiryMap.mainSuit': thenS_.txdiagnosis_log_main_suit,
                'inquiryMap.presentIllness': thenS_.txdiagnosis_log_present_illness
            })
            this.publicUtil_getInquiryLogDetails();
        }).catch(err => {
            $service.showToast(err.msg);
        })
    },
    // 保存诊断
    updateDiagnosis(list) {
        let arr = []
        list.forEach((item) => {
            item.diagnosis = item.name
            arr.push(item.name)
        })
        let params = {
            "diagnosis": list,
            "id": logId,
        }
        app.http.updateDiagnosis(params).then(res => {
            $service.showToast(res.msg);
            this.data.inquiryMap.diagnosis = arr.join();
            this.setData({
                'inquiryMap.diagnosis': this.data.inquiryMap.diagnosis
            })
            this.publicUtil_getInquiryLogDetails();
        }).catch(err => {
            $service.showToast(err.msg);
        })
    },

    // --------
    // 输入框监听
    txdiagnosis_inputChange(e) {
        var value = e.detail.value;
        var index = e.currentTarget.dataset.index; //
        if (index == 1) {
            console.log(thenS_.tabactive);
            if (thenS_.tabactive == 0) {
                thenS_.txdiagnosis_iinquiry_patient_allergy_details = value
            } else if (thenS_.tabactive == 1) {
                thenS_.txdiagnosis_log_main_suit = value
            } else if (thenS_.tabactive == 2) {
                thenS_.txdiagnosis_log_present_illness = value
            } else if (thenS_.tabactive == 3) {
                thenS_.txdiagnosis_log_history_present_illness = value
            } else if (thenS_.tabactive == 4) {
                thenS_.txdiagnosis_lof_diagnosis = value
            }
        } else if (index == 2) {
            thenS_.template_name = value
        } else if (index == 3) {
            thenS_.template_details = value
        } else if (index == 4) {
            thenS_.txdiagnosis_name = value
        } else if (index == 5) {
            // thenS_.inputtext = ''
            for (var i = 0; i < thenS_.diagnosis_list.length; i++) {
                if (thenS_.diagnosis_list[i].name == numText) {
                    thenS_.diagnosis_list[i].name = thenS_.diagnosis_list[i].name + '(' + value + ')'
                }
            }
        } else if (index == 6) {
            thenS_.isdiagnosisText = value
        }
        this.setData({
            txdiagnosis_iinquiry_patient_allergy_details: thenS_.txdiagnosis_iinquiry_patient_allergy_details, //过敏史
            txdiagnosis_log_main_suit: thenS_.txdiagnosis_log_main_suit, //主诉
            txdiagnosis_log_present_illness: thenS_.txdiagnosis_log_present_illness, //现病史
            txdiagnosis_log_history_present_illness: thenS_.txdiagnosis_log_history_present_illness, //既往史
            txdiagnosis_lof_diagnosis: thenS_.txdiagnosis_lof_diagnosis, //诊断
            template_name: thenS_.template_name, //模板名称
            template_details: thenS_.template_details, //模板内容
            txdiagnosis_name: thenS_.txdiagnosis_name,
            inputtext: thenS_.inputtext,
            diagnosis_list: thenS_.diagnosis_list,
            activeIndex: '',
            isdiagnosisText: thenS_.isdiagnosisText
        })
        this.getdoctorSide_personal_inquiry()
    },
    // 诊断 主诉 现病史 既往史 按钮
    async txdiagnosis_btn(e) {
        var this_ = this
        var index = e.currentTarget.dataset.index; //1清空 2保存模板() 3保存
        if (index == 1) {
            if (thenS_.tabactive == 0) {
                thenS_.txdiagnosis_iinquiry_patient_allergy_details = ''
            } else if (thenS_.tabactive == 1) {
                thenS_.txdiagnosis_log_main_suit = ''
            } else if (thenS_.tabactive == 2) {
                thenS_.txdiagnosis_log_present_illness = ''
            } else if (thenS_.tabactive == 3) {
                thenS_.txdiagnosis_log_history_present_illness = ''
            } else if (thenS_.tabactive == 4) {
                thenS_.diagnosis_list = []
            }
            this.setData({
                txdiagnosis_iinquiry_patient_allergy_details: thenS_.txdiagnosis_iinquiry_patient_allergy_details, //过敏史
                txdiagnosis_log_main_suit: thenS_.txdiagnosis_log_main_suit, //主诉
                txdiagnosis_log_present_illness: thenS_.txdiagnosis_log_present_illness, //现病史
                txdiagnosis_log_history_present_illness: thenS_.txdiagnosis_log_history_present_illness, //既往史
                diagnosis_list: thenS_.diagnosis_list //诊断
            })
            this.getdoctorSide_personal_inquiry()
        } else if (index == 2) { //保存模板
            this.setData({
                txdiagnosis_isdetalis: true,
                txdiagnosis_isdetalistype: 1,
                template_type: '', //模板类型
                template_name: '', //模板名称
                template_details: '' //模板内容
            })
        } else if (index == 3) { //保存
            if (thenS_.tabactive == 0) { //药物过敏史
                this.updateAllergyHistory();
            } else if (thenS_.tabactive == 1 || thenS_.tabactive == 2 || thenS_.tabactive == 3) { //主诉、现病史、既往史 
                this.updateInquiryLog();
            } else if (thenS_.tabactive == 4) { //诊断
                this.updateDiagnosis(thenS_.diagnosis_list);
            }
            this_.closeBox('', 1); //关闭窗口
        } else if (index == 4) { //取消生成个人模板
            this.setData({
                txdiagnosis_isdetalis: false,
                txdiagnosis_isdiagnosis: false,
                isdiagnosisText: thenS_.isdiagnosisText
            })
        } else if (index == 5) { //确认生成 编辑个人模板
            if ($service.isUndefinedAndEmpty(thenS_.template_type)) {
                $service.showToast('请选择模板类型');
                return;
            }
            if ($service.isUndefinedAndEmpty(thenS_.template_name)) {
                $service.showToast('请输入模板名称');
                return;
            }
            if ($service.isUndefinedAndEmpty(thenS_.template_details)) {
                $service.showToast('请输入模板内容');
                return;
            }
            if (thenS_.template_type == "主诉") {
                var template_type = "1"
            } else if (thenS_.template_type == "现病史") {
                var template_type = "2"
            } else if (thenS_.template_type == "既往史") {
                var template_type = "3"
            }
            let params = {}
            if (thenS_.txdiagnosis_isdetalistype == 1) {
                params = {
                    "templateType": template_type,
                    "templateName": thenS_.template_name,
                    "templateDetails": thenS_.template_details
                }
            } else {
                params = {
                    "id": template_id,
                    "templateType": template_type,
                    "templateName": thenS_.template_name,
                    "templateDetails": thenS_.template_details
                }
            }
            console.log(params)
            app.http.newTemplate(params).then(res => {
                $service.showToast(res.msg)
                this_.setData({
                    template_type: '', //模板类型
                    template_name: '', //模板名称
                    template_details: '', //模板内容
                    txdiagnosis_isdetalis: false
                })
                this_.getdoctorSide_personal_inquiry()
            }).catch(err => {
                $service.showToast(err.msg)
            })
        } else if (index == 6) { //打开自定义诊断
            for (var i = 0; i < thenS_.diagnosis_list.length; i++) {
                if (thenS_.diagnosis_list[i].type == "1") {
                    thenS_.isdiagnosisText = thenS_.diagnosis_list[i].name.substring(6, 1000)
                }
            }
            this.setData({
                txdiagnosis_isdiagnosis: true,
                isdiagnosisText: thenS_.isdiagnosisText
            })
        } else if (index == 7) { //保存诊断
            var num = 0
            for (var i = 0; i < thenS_.diagnosis_list.length; i++) {
                if (thenS_.diagnosis_list[i].type == "1") {
                    num = 1
                    thenS_.diagnosis_list[i].name = '自定义诊断：' + thenS_.isdiagnosisText
                }
            }
            if (num == 0) {
                var json = {
                    "name": '自定义诊断：' + thenS_.isdiagnosisText,
                    "type": "1",
                    "diagnosisId": 0,
                }
                thenS_.diagnosis_list.push(json)
            }
            this.setData({
                txdiagnosis_isdiagnosis: false,
                diagnosis_list: thenS_.diagnosis_list
            })
        }
    },
    //填写诊断、主诉、过敏史等
    getdoctorSide_personal_inquiry() { //index 0过敏史 1 主诉 2现病史 3既往史 4诊断
        if (thenS_.tabactive == 0) {
            thenS_.text = thenS_.txdiagnosis_iinquiry_patient_allergy_details
        } else if (thenS_.tabactive == 1) {
            thenS_.text = thenS_.txdiagnosis_log_main_suit
        } else if (thenS_.tabactive == 2) {
            thenS_.text = thenS_.txdiagnosis_log_present_illness
        } else if (thenS_.tabactive == 3) {
            thenS_.text = thenS_.txdiagnosis_log_history_present_illness
        }
        this.setData({
            text: thenS_.text
        })
        if (thenS_.tabactive == 1 || thenS_.tabactive == 2 || thenS_.tabactive == 3) {
            this.getTemplate();
        } else if (thenS_.tabactive == 4) {
            this.getIcdList();
        }
    },
    //诊断遍历
    getlofdiagnosis(diagnosisText, num) {
        var nameList = [];
        var numC = 0

        if (num == 1) { //map
            if (!$service.isUndefinedAndEmpty(diagnosisText)) {
                var lofdiagnosislist = diagnosisText.split(",")
                for (var i = 0; i < lofdiagnosislist.length; i++) {
                    var index = lofdiagnosislist[i].indexOf('自定义诊断');
                    if (index > -1) {
                        var json = {
                            "name": lofdiagnosislist[i],
                            "type": "1",

                        }
                    } else {
                        numC++
                        var json = {
                            "name": lofdiagnosislist[i],
                            "type": "2",
                            "num": numC
                        }
                    }
                    nameList.push(json);
                }
            }
        } else if (num == 2) { //list
            for (var i = 0; i < diagnosisText.length; i++) {
                if (diagnosisText[i].type == "1") {
                    var json = {
                        "name": diagnosisText[i].name,
                        "type": "1",

                    }
                } else {
                    numC++
                    var json = {
                        "name": diagnosisText[i].name,
                        "type": "2",
                        "num": numC
                    }
                }
                nameList.push(json);
            }

        }
        this.setData({
            diagnosis_list: nameList,
        })


    },
    // 主诉 2现病史 3既往史 模版
    getTemplate() {
        let params = {
            "isPersonalTemplate": Number(thenS_.mould),
            "templateName": thenS_.txdiagnosis_name,
            "templateType": thenS_.tabactive, //1 主诉 2现病史 3既往史
        }
        app.http.getTemplate(params).then(res => {
            this.setData({
                templateList: res.data.list
            })
        }).catch(err => {
            $service.showToast(err.msg)
        })
    },
    // 诊断列表
    getIcdList() {
        app.http.getIcdList({
            keyword: thenS_.txdiagnosis_name
        }).then(res => {
            this.setData({
                templateList: res.data.list
            })
        }).catch(err => {
            $service.showToast(err.msg)
        })
    },
    txdiagnosis_taptab(e) {
        var index = e.currentTarget.dataset.index;
        var num = e.currentTarget.dataset.num;
        if (num == 1) {
            thenS_.tabactive = index
        } else if (num == 2) {
            console.log(index)
            thenS_.mould = index
        }
        this.setData({
            mould: thenS_.mould,
            tabactive: thenS_.tabactive
        })
        this.getdoctorSide_personal_inquiry()
    },
    taptemplateList(e) {
        var this_ = this
        var index = e.currentTarget.dataset.index; //下标
        var num = e.currentTarget.dataset.num; //1删除模板 2编辑模板 3 引用模板
        if (num == 1) {
            wx.showModal({
                title: '温馨提示',
                content: '确定要删除当前模板？',
                success(res) {
                    if (res.confirm) {
                        var jsonData = {
                            "id": thenS_.templateList[index].id
                        }
                        app.http.deleteTemplate(jsonData).then(res => {
                            this_.getdoctorSide_personal_inquiry()
                        }).finally(res => {
                            $service.showToast(res.msg)
                        })
                    }
                }
            })
        } else if (num == 2) { //编辑模板
            template_id = thenS_.templateList[index].id;
            if (thenS_.tabactive == "1") {
                var template_type = "主诉"
            } else if (thenS_.tabactive == "2") {
                var template_type = "现病史"
            } else if (thenS_.tabactive == "3") {
                var template_type = "既往史"
            }
            this.setData({
                txdiagnosis_isdetalis: true,
                txdiagnosis_isdetalistype: 2,
                template_type: template_type, //模板类型
                template_name: thenS_.templateList[index].templateName, //模板名称
                template_details: thenS_.templateList[index].templateDetails //模板内容
            })
        } else if (num == 3) {
            if (!$service.isUndefinedAndEmpty(thenS_.text)) {
                if (thenS_.text.indexOf(thenS_.templateList[index].templateDetails) > -1) {
                    $service.showToast('请勿重复添加');
                    return;
                }
                var valtext = thenS_.text + '、' + thenS_.templateList[index].templateDetails;
            } else {
                var valtext = thenS_.templateList[index].templateDetails;
            }
            if (thenS_.tabactive == 1) {
                thenS_.txdiagnosis_log_main_suit = valtext
            } else if (thenS_.tabactive == 2) {
                thenS_.txdiagnosis_log_present_illness = valtext
            } else if (thenS_.tabactive == 3) {
                thenS_.txdiagnosis_log_history_present_illness = valtext
            } else if (thenS_.tabactive == 4) {
                thenS_.txdiagnosis_lof_diagnosis = valtext
            }
            this.setData({
                txdiagnosis_iinquiry_patient_allergy_details: thenS_.txdiagnosis_iinquiry_patient_allergy_details, //过敏史
                txdiagnosis_log_main_suit: thenS_.txdiagnosis_log_main_suit, //主诉
                log_present_illness: thenS_.txdiagnosis_log_present_illness, //现病史
                txdiagnosis_log_history_present_illness: thenS_.txdiagnosis_log_history_present_illness, //既往史
                txdiagnosis_lof_diagnosis: thenS_.txdiagnosis_lof_diagnosis //诊断
            })
            this.getdoctorSide_personal_inquiry()
        }
    },
    txdiagnosis_tap_usage(e) {
        var num = e.currentTarget.dataset.num; //
        if (num == 1) {
            thenS_.txdiagnosis_islist2 = !thenS_.txdiagnosis_islist2
        } else {
            var index = e.currentTarget.dataset.index; //0主诉 1现病史 2既往史
            thenS_.template_type = index
            thenS_.txdiagnosis_islist2 = false
        }
        this.setData({
            template_type: thenS_.template_type,
            txdiagnosis_islist2: thenS_.txdiagnosis_islist2
        })
    },
    //删除诊断列表
    delImg(e) {
        var index = e.currentTarget.dataset.index; //
        var list = thenS_.diagnosis_list
        for (var i = 0; i < thenS_.diagnosis_list.length; i++) {
            if (index == i) {
                if (thenS_.diagnosis_list[i].type == "1") {
                    thenS_.isdiagnosisText = ''
                }
                list.splice(i, 1)
            }
        }
        this.setData({
            isdiagnosisText: thenS_.isdiagnosisText
        })
        this.getlofdiagnosis(list, 2)
    },
    //选中诊断列表
    templateListtap(e) {
        var index = e.currentTarget.dataset.index; //
        var num = 0;
        for (var i = 0; i < thenS_.diagnosis_list.length; i++) {
            if (thenS_.diagnosis_list[i].type == 2) {
                num++
            }
            if (thenS_.diagnosis_list[i].name == thenS_.templateList[index].icdName) {
                $service.showToast('有重复诊断!');
                return
            }
        }
        var json = {
            "name": thenS_.templateList[index].icdName,
            "diagnosisId": thenS_.templateList[index].id,
            "type": "2",
            "num": (num + 1)
        }
        thenS_.diagnosis_list.push(json)
        numText = json.name
        this.setData({
            activeIndex: index, //
            diagnosis_list: thenS_.diagnosis_list
        })

    },



    //---------------- 药品详情信息
    //数据
    publicUtil_getDrugDetail: function (drug_id) {
        if (this.data.hisType && this.data.storeData.group_no == 0) { // 廉江his
            let index = this.data.medListIndex;
            let drugData = this.data.drugList[index]
            console.log(drugData)
            let drugMap = {
                dosageName: drugData.dosageName,
                drugSpecifications: drugData.drugSpecifications,
                commonName: drugData.drugCommonName,
                drugName: drugData.drugName,
                drugPrice: drugData.drugPrice,
                storeName: drugData.storeName,
                drugCompany: drugData.manufactorName || '--',
                drugOrigin: drugData.productionPlace,
                alias: "--",
                drugType: drugData.typeName,
                drugImg: "../../../static/images/order_img.png"
            };
            this.setData({
                ypxx_drugMap: drugMap
            })
          return
        }
        if (this.data.paymentMethodNum == 1) {
            console.log('标志',this.data.medListIndex);
            let index = this.data.medListIndex;
            let drugList = this.data.drugList
            console.log(drugList);
            let drugMap = {
                commonName: "--",
                drugName: drugList[index].drugName,
                drugPrice: "--",
                storeName: drugList[index].storeName,
                drugCompany: "--",
                drugOrigin: "--",
                alias: "--",
                drugType: drugList[index].drugpype,
                drugImg: "../../../static/images/order_img.png"
            };
            this.setData({
                ypxx_drugMap: drugMap
            })
        } else {
            app.http.getDrugSpeciFicationDetail({
                id: drug_id
            }).then(res => {
                console.log(res);
                var drugMap = res.data;
                drugMap.drugInstructions = $service.nothingFun(drugMap.drugInstructions, '暂无药品说明详情');
                if (drugMap.drugType == 1) {
                    drugMap.drugType = '中药'
                } else if (drugMap.drugType == 2) {
                    drugMap.drugType = '西药 '
                } else {
                    drugMap.drugType = '中成药'
                }
                this.setData({
                    ypxx_drugMap: drugMap
                })
            }).catch(err => {
                $service.showToast(err.msg);
            })
        }
    },
    //修改患者资料
    //职业
    publicUtil_getUtilTable10: function () {
        app.http.getOccupationList().then(res => {
            this.setData({
                xghzzl_list: res.data.list
            })
        })
    },
    //获取病种列表
    getDiseaseNameList() {
      app.http.getDiseaseNameList().then(res => {
        let array = [...res.data.list];
        this.setData({
            diseaseArray: array
        })
      })
    },
    //选择出生年月
    bindDateChange: function (e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        thenS_.inquiryMap2.patientBirthday = e.detail.value
        this.setData({
            inquiryMap2: thenS_.inquiryMap2
        })
    },
    //选择框
    xghzzl_choosetap(e) {
        var index = e.currentTarget.dataset.index;
        var num = e.currentTarget.dataset.num;
        if (num == 1) {
            this.data.inquiryMap2.patientSex = index
        } else if (num == 2) {
            this.data.inquiryMap2.isMarried = index
        } else if (num == 3) {
            this.data.inquiryMap2.isDrugAllergy = index;
            if (index == 0) {
                this.data.inquiryMap2.patientAllergyDetails = '';
            }
        } else if (num == 4) {} else if (num == 5) {
            this.data.xghzzl_isshow = !this.data.xghzzl_isshow
            this.data.tsqk_isshow = false
        } else if (num == 6) {
            this.data.inquiryMap2.patientProfession = this.data.xghzzl_list[index].occupationName
            this.data.inquiryMap2.patientProfessionCode = this.data.xghzzl_list[index].id
        } else if (num == 7) {
          this.data.tsqk_isshow = !this.data.tsqk_isshow
          this.data.xghzzl_isshow = false
        } else if (num == 8) {
          this.data.inquiryMap2.isChildOption = this.data.tsqk_list[index].value
        } else if (num == 11) {
            this.data.inquiryMap2.paymentMethod = index
        }
        this.setData({
            tsqk_isshow: this.data.tsqk_isshow,
            inquiryMap2: this.data.inquiryMap2,
            xghzzl_isshow: this.data.xghzzl_isshow
        })
    },
    //监听input
    xghzzl_inputChange(e) {
        var name = e.detail.value;
        var index = e.currentTarget.dataset.index;
        if (index == 0) {
            thenS_.inquiryMap2.patientName = name;
        } else if (index == 1) {
            thenS_.inquiryMap2.patientPhone = name;
        } else if (index == 2) {
            thenS_.inquiryMap2.patientMaritalStatus = name;
        } else if (index == 3) {
            thenS_.inquiryMap2.patientIdcard = name;
            if (this.data.isAuto == 1 && !logId) {
              this.getBirthdatByIdNo(name)
            }
        } else if (index == 4) {
            thenS_.inquiryMap2.patientWeight = name;
        } else if (index == 8) {
          thenS_.inquiryMap2.patientHeight = name;
        } else if (index == 5) {
            this.data.isAuto == 0 ? thenS_.inquiryMap2.patientAddress = name : thenS_.inquiryMap2.autonomousAddress = name
        } else if (index == 6) {
            thenS_.inquiryMap2.patientAllergyDetails = name;
        } else if (index == 7) {}
        this.setData({
            inquiryMap2: thenS_.inquiryMap2
        })
        // 自主开方搜索就诊人
        if ((index == 1 || index == 3) && thenS_.inquiryMap2.patientIdcard && thenS_.inquiryMap2.patientPhone && thenS_.isAuto == 1 && !logId) {
          if ($service.validateElement('idCard', thenS_.inquiryMap2.patientIdcard) && $service.validateElement('mobile', thenS_.inquiryMap2.patientPhone)) {
            this.getSearchDoctorInquiryPatientInfoList()
          }
        }
    },
    //病种Picker选择
    diseasePickerChange(e) {
        this.setData({
            diseaseMessage: this.data.diseaseArray[e.detail.value]
        })
        let params = {
            "diseaseCode": this.data.diseaseArray[e.detail.value].diseaseCode,
            "diseaseName": this.data.diseaseArray[e.detail.value].diseaseName,
            "logId": logId
        }
        app.http.updateDiseaseName(params).then(res=>{
            console.log(res)
        })
    },
    //咨询
    consultationBtn() {
        var this_ = this;
        if (!thenS_.inquiryMap2.patientName) {
            $service.showToast('请输入名称');
            return;
        }
        if (thenS_.inquiryMap2.patientSex == 3) {
            $service.showToast('请选择性别');
            return;
        }
        if (thenS_.inquiryMap2.paymentMethod == 3) {
            $service.showToast('请选择付费类型');
            return;
        }
        if ($service.isUndefinedAndEmpty(thenS_.inquiryMap2.patientPhone)) {
            $service.showToast('请输入手机号');
            return;
        }
        if (thenS_.inquiryMap2.patientPhone.length != 11) {
            $service.showToast('请输入正确的手机号');
            return;
        }

        if (!$service.validateElement('idCard', thenS_.inquiryMap2.patientIdcard)) {
            $service.showToast('请输入身份证号');
            return;
        }
        if (thenS_.inquiryMap2.patientBirthday == '请选择出生日期') {
            $service.showToast('请选择出生日期');
            return;
        }
        if (thenS_.inquiryMap2.isMarried === '' || thenS_.inquiryMap2.isMarried === null) {
            $service.showToast('请选择是否婚配');
            return;
        }
        if (thenS_.inquiryMap2.isDrugAllergy == 3) {
            $service.showToast('请选择是否药物过敏');
            return;
        }
        if (thenS_.inquiryMap2.patientWeight == '') {
            thenS_.inquiryMap2.patientWeight = 0
        }
        //医保
        if(thenS_.paymentMethodNum==1&& thenS_.diseaseMessage=="" && this.data.hospitalType == 'zhuhai'){
            $service.showToast('请选择病种信息');
            return;
        }
         // 地区
        if (this.data.isAuto == 1 && !thenS_.inquiryMap2.addressCity) {
          $service.showToast('请选择地区');
          return;
        }
        // 地址
        if (this.data.isAuto == 1 && !thenS_.inquiryMap2.autonomousAddress) {
          $service.showToast('请输入详细地址');
          return;
        }
        var params = {
            "id": inquiryPatientId, //患者id
            "patientName": thenS_.inquiryMap2.patientName, //名称
            "patientIdcard": thenS_.inquiryMap2.patientIdcard, //身份证
            "patientSex": thenS_.inquiryMap2.patientSex, //性别 1男 0女
            "patientBirthday": thenS_.inquiryMap2.patientBirthday, //出生日期 1995-08-01
            "patientPhone": thenS_.inquiryMap2.patientPhone, //手机号
            "isMarried": thenS_.inquiryMap2.isMarried, //是否已婚 0否 1是
            "patientMaritalStatus": thenS_.inquiryMap2.patientMaritalStatus, //籍贯
            "patientWeight": thenS_.inquiryMap2.patientWeight, //体重
            "patientProfession": thenS_.inquiryMap2.patientProfession, //职业
            "patientProfessionCode": thenS_.inquiryMap2.patientProfessionCode, //职业
            "patientAddress": thenS_.inquiryMap2.patientAddress, //住址
            "autonomousAddress": thenS_.inquiryMap2.autonomousAddress, // 自主开方住址
            "addressCity": thenS_.inquiryMap2.addressCity, // 自主开方住址
            "isDrugAllergy": thenS_.inquiryMap2.isDrugAllergy, //是否药物过敏 .0否 1是
            "patientAllergyDetails": thenS_.inquiryMap2.patientAllergyDetails, //药物过敏史
            "paymentMethod": thenS_.inquiryMap2.paymentMethod, //付费类型 1自费缴费 2
            "patientHeight": thenS_.inquiryMap2.patientHeight, // 身高
        }
        if (this.data.isAuto == 0) { // 非自主开方修改就诊人信息
          app.http.updateInquiryPatientInfo(params).then(res => {
              $service.showToast(res.msg)
              this_.closeBox('', 1)
          }).catch(err => {
              $service.showToast(err.msg)
          })
        } else {
          params.isChildOption = thenS_.inquiryMap2.isChildOption
          if (logId) {params.logId = logId}
          params.patientId = thenS_.inquiryMap2.id
          this.doctorAddOrupdatePatientInfo(params)
        }
    },

    //---------- 保存模板

    //list 工具
    publicUtil_getUtilTable78: function () {
        this.getDrugUsageList(3);
        this.getDrugUsageList(4)
    },
    bcmb_tap_usage(e) {
        var num = e.currentTarget.dataset.index;
        if (num == 0) { //服用方法
            thenS_.bcmb_islist = !thenS_.bcmb_islist
            thenS_.bcmb_islist2 = false
        } else if (num == 1) { //服用要求
            thenS_.bcmb_islist2 = !thenS_.bcmb_islist2
            thenS_.bcmb_islist = false
        }
        this.setData({
            bcmb_islist: thenS_.bcmb_islist,
            bcmb_islist2: thenS_.bcmb_islist2
        })
    },
    //选择用法、用量单位、频次、嘱托
    bcmb_chooselist(e) {
        var index = e.currentTarget.dataset.index;
        var num = e.currentTarget.dataset.num;
        if (num == 0) { //用法
            thenS_.bcmb_prescription_taking = thenS_.list2[index].usageName
        } else if (num == 1) { //用量单位
            thenS_.bcmb_prescription_requirements = thenS_.list3[index].usageName
        }
        this.setData({
            bcmb_prescription_taking: thenS_.bcmb_prescription_taking,
            bcmb_prescription_requirements: thenS_.bcmb_prescription_requirements,
            bcmb_islist: false,
            bcmb_islist2: false
        })
    },
    //input监听
    bcmb_inputChange(e) {
        var index = e.currentTarget.dataset.index;
        if (index == 1) { //用量
            this.setData({
                bcmb_queryName: e.detail.value
            })
            this.doctorSide_personal_prescription_getDiagnosisList()
        } else if (index == 2) { //天数
            thenS_.bcmb_prescription_name = e.detail.value
        } else if (index == 3) { //盒数
            thenS_.bcmb_prescription_num = e.detail.value
        } else if (index == 4) { //嘱托
            thenS_.bcmb_bz = e.detail.value
        }
        this.setData({
            bcmb_prescription_name: thenS_.bcmb_prescription_name,
            bcmb_prescription_num: thenS_.bcmb_prescription_num,
            bcmb_bz: thenS_.bcmb_bz
        })
    },
    doctorSide_personal_prescription_getDiagnosisList: function () {
        let params = {
            "keyword": this.data.bcmb_queryName
        }
        app.http.getIcdList(params).then(res => {
            console.log(res.data.list)
            var diagnosisList = res.data.list; //列表
            if (diagnosisList.length == 0) {
                thenS_.bcmb_isullist = false;
                this.setData({
                    bcmb_icd_name: thenS_.bcmb_icd_name
                })
                $service.showToast('暂无数据，请输入正确的诊断名称')
            } else {
                thenS_.bcmb_isullist = true
            }
            this.setData({
                bcmb_diagnosisList: diagnosisList,
                bcmb_isullist: thenS_.bcmb_isullist
            })
        }).catch(err => {
            $service.showToast(err.msg);
        })
    },
    tapdiagnosisList(e) {
        var index = e.currentTarget.dataset.index;
        bcmb_diagnosis_id = thenS_.bcmb_diagnosisList[index].id
        if ($service.isUndefinedAndEmpty(thenS_.bcmb_prescription_name)) {
            thenS_.bcmb_prescription_name = thenS_.bcmb_diagnosisList[index].icdName
        }
        this.setData({
            bcmb_icd_name: thenS_.bcmb_diagnosisList[index].icdName,
            bcmb_prescription_name: thenS_.bcmb_prescription_name,
            bcmb_icd_id: thenS_.bcmb_diagnosisList[index].id,
            bcmb_isullist: false
        })
    },
    bcmb_cancel() {
        this.setData({
            bcmb_isullist: false
        })
    },
    cancel(e) {
        this.setData({
            bcmb_icd_name: thenS_.bcmb_icd_name,
            bcmb_isullist: false
        })
    },
    bcmb_qrBtn() {
        var this_ = this;
        if ($service.isUndefinedAndEmpty(thenS_.bcmb_icd_name)) {
            $service.showToast('请先选择诊断名称');
            return;
        }
        if ($service.isUndefinedAndEmpty(thenS_.bcmb_prescription_name)) {
            $service.showToast('请先输入模板名称');
            return;
        }
        if (thenS_.bcmb_type == 1) { //健康指导
            let params = {
                "diagnosisId": bcmb_diagnosis_id,
                "guidanceContent": template_prescriptionList.guidance_content,
                "guidanceName": thenS_.bcmb_prescription_name
            }
            console.log(params)
            app.http.addHealthGuidanceModel(params).then(res => {
                $service.showToast('保存模板成功')
                this.getHealthGuidanceModelList();
                this_.closeBox('', 1)
            }).catch(err => {
                $service.showToast(err.msg)
            })
        } else { //处方
            //保存处方模块
            var jsonData = {
                "drugs": template_prescriptionList.detailsList,
                "diagnosisId": bcmb_diagnosis_id, //	诊断id
                "prescriptionType": thenS_.drug_type, //处方类型 1中药 2西药
                "prescriptionPrice": template_prescriptionList.prescription_price, //	处方金额
                "prescriptionName": thenS_.bcmb_prescription_name, //处方名称 中药时使用
                "remarks": thenS_.bcmb_bz, //备注
                "storeId": template_prescriptionList.preType == 2 ? template_prescriptionList.storeId : thenS_.storeId, //来源ID 
                "storeName": template_prescriptionList.preType == 2 ? template_prescriptionList.storeName : thenS_.storeName //来源
            }
            if (thenS_.bcmb_type != 1) {
                if (thenS_.drug_type == 1) { //1中药
                    if ($service.isUndefinedAndEmpty(thenS_.bcmb_prescription_taking)) {
                        $service.showToast('请先选择服用方法');
                        return;
                    }
                    if ($service.isUndefinedAndEmpty(thenS_.bcmb_prescription_num)) {
                        $service.showToast('请先输入付数');
                        return;
                    }
                    jsonData.prescriptionNum = thenS_.bcmb_prescription_num; //付数 中药时使用
                    jsonData.prescriptionTaking = thenS_.bcmb_prescription_taking; //服用方法 中药时使用
                    jsonData.prescriptionRequirements = thenS_.bcmb_prescription_requirements; //服用要求 中药时使用
                }
            }
            app.http.addPrescriptionTemplate(jsonData).then(res => {
                $service.showToast(res.msg)
                this_.publicUtil_getInquiryLogDetails()
                this_.getalldo()
                this_.closeBox('', 1)
            }).catch(err => {
                $service.showToast(err.msg);
            })
        }
    },
    // 查看详情 图片
    getEstablishPdf(id, type, value) { // 1=生成住院建议书 2=生成健康指导 3=生成检验检查单 4=生成处方单
        let params = {
            "id": id,
            "resourceType": type,
            "type": 2,
            "template": value
        }
        app.http.getEstablishPdf(params, true).then(res => {
            let imgUrl = res.data.url;
            switch (type) {
                case 1:
                    thenS_.hospitalization_imgurl = imgUrl
                    break;
                case 2:
                    thenS_.guidance_imgurl = imgUrl
                    break;
                case 3:
                    thenS_.checklist_imgurl = imgUrl
                    break;
                case 4:
                    thenS_.prescription_imgurl = imgUrl
                    break;
                case 5:
                    thenS_.application_imgurl = imgUrl
                    break;
            }
            this.setData({
                prescription_imgurl: thenS_.prescription_imgurl,
                guidance_imgurl: thenS_.guidance_imgurl,
                hospitalization_imgurl: thenS_.hospitalization_imgurl,
                checklist_imgurl: thenS_.checklist_imgurl,
                application_imgurl: thenS_.application_imgurl
            })
        }).catch(err => {
            $service.showToast(err.msg)
        })
    },
    
    // 撤销住院建议
    hospitalizationTap(e) {
        app.http.deleteInquiryLogHospitalization({
            logId: Number(logId)
        }).then(res => {
            $service.showToast('撤销成功')
            this.publicUtil_getInquiryLogDetails()
            this.setData({
                openPageBox: 0
            })
            this.bottom()
        }).catch(err => {
            $service.showToast(err.msg)
        })
    },
    //聚焦
    tapinputShowed(e) {
        var index = e.currentTarget.dataset.num;
        if (index == 1) {
            this.setData({
                isinputShowed: true,
                inputShowed: true
            })
        } else if (index == 2) {
            this.setData({
                isinputShowed2: true,
                inputShowed2: true
            })
        } else if (index == 3) {
            this.setData({
                isinputShowed3: true,
                inputShowed3: true
            })
        } else if (index == 4) {
            this.setData({
                isinputShowed4: true,
                inputShowed4: true
            })
        } else if (index == 5) {
            this.setData({
                isinputShowed5: true,
                inputShowed5: true
            })
        } else if (index == 6) {
            this.setData({
                isinputShowed6: true,
                inputShowed6: true
            })
        } else if (index == 7) {
            this.setData({
                isinputShowed7: true,
                inputShowed7: true
            })
        }

    },
    //失焦
    bindblurisinputShowed(e) {
        var index = e.currentTarget.dataset.num;
        if (index == 1) {
            this.setData({
                isinputShowed: false,
                inputShowed: false
            })
        } else if (index == 2) {
            this.setData({
                isinputShowed2: false,
                inputShowed2: false
            })
        } else if (index == 3) {
            this.setData({
                isinputShowed3: false,
                inputShowed3: false
            })
        } else if (index == 4) {
            this.setData({
                isinputShowed4: false,
                inputShowed4: false
            })
        } else if (index == 5) {
            this.setData({
                isinputShowed5: false,
                inputShowed5: false
            })
        } else if (index == 6) {
            this.setData({
                isinputShowed6: false,
                inputShowed6: false
            })
        } else if (index == 7) {
            this.setData({
                isinputShowed7: false,
                inputShowed7: false
            })
        }
    },
    /** 分诊 */
    //医生列表
    getOnlineDoctorList() {
        let params = {
            "departmentId": thenS_.fzdepartment_id,
            "keyWord": thenS_.fzdoctor_name,
        }
        app.http.getOnlineDoctorList(params).then(res => {
            let list = $service.deepClone(res.data.list)
            this.setData({
                fzdoctorList: list.filter(item => item.id !== JSON.parse($service.getStore('userInfo')).id)
            })
        }).catch(err => {
            $service.showToast(err.msg)
        })
    },
    // 科室类表
    getDepartmentListPc() {
        app.http.getDepartmentListPc().then(res => {
            this.setData({
                fzdepartmentList: res.data.list
            })
        })
    },
    //分诊监听input框
    fzinputChange(e) {
        this.setData({
            fzdoctor_name: e.detail.value
        })
    },
    //分诊搜索
    fzqr_Btn() {
        this.getOnlineDoctorList();
        this.setData({
            fzisshow: false
        })
    },
    //分诊弹窗
    fztapactive(e) {
        console.log(e)
        var num = e.currentTarget.dataset.num;
        if (num == 0) {
            this.data.fzisshow = !this.data.fzisshow
            this.setData({
                fzisshow: this.data.fzisshow
            })
        } else {
            var index = e.currentTarget.dataset.index;
            if (index == -1) {
                thenS_.fzdepartment_id = ''
            } else {
                thenS_.fzdepartment_id = thenS_.fzdepartmentList[index].id
            }
            this.setData({
                fzactivenum: index,
                fzdepartment_id: thenS_.fzdepartment_id
            })
        }
    },
    //分诊
    addTriageNote(e) {
        var index = e.currentTarget.dataset.index;
        app.webSocket.sendWebSocketMsg({
            data: {
                "logId": logId, // 被分诊的问诊id
                "dispatchedDoctorId": thenS_.fzdoctorList[index].id, // 被分诊的医生id     
                "packageType": 15
            },
            success: () => {
                $service.showToast('以发送申请')
            },
            fail: () => {
                $service.showToast('申请失败')
            }
        })
    },
    

    // oss信息
    ossPolicy() {
        app.http.ossPolicy().then(res => {
            oosParams = res.data;
        })
    },
    // 上传图片 newok
    uploadImg: function () {
        this.setData({
            isWithdrawShow: false
        })
        isImgShow = true
        var this_ = this;
        wx.chooseImage({
            count: 1,
            success: function (res) {
                const tempFilePaths = res.tempFilePaths;
                wx.uploadFile({
                    url: oosParams.host,
                    filePath: tempFilePaths[0],
                    name: 'file',
                    formData: {
                        name: $service.randomFilename(tempFilePaths[0]),
                        key: oosParams.dir + $service.randomFilename(tempFilePaths[0]),
                        dir: oosParams.dir,
                        policy: oosParams.policy,
                        OSSAccessKeyId: oosParams.accessid,
                        success_action_status: "200", //让服务端返回200,不然，默认会返回204
                        callback: oosParams.callback,
                        signature: oosParams.signature
                    },
                    success: (uploadFileRes) => {
                        let imgData = JSON.parse(uploadFileRes.data)
                        if (imgData.code === 1) {
                            let data = {
                                "msgText": imgData.data.filename, // 信息体
                                "friendId": imId, // 接收方的用户imID
                                "msgType": 3, // 消息类型；0文字消息、1固定表情 3 图片url
                                "inquiryLogId": logId,
                                "msgUserName": this_.data.inquiryMap.doctorName,
                                "msgDate": $service.getDate(), // 发送时间
                                "packageType": 3, // 信息包类型
                            }
                            app.webSocket.sendWebSocketMsg({
                                data,
                                success: (res) => {
                                    this_.setData({
                                        increase: false
                                    })
                                },
                                fail: (err) => {
                                    $service.showToast(err.errMsg);
                                }
                            })
                        }
                    },
                    fail: (res => {
                        $service.showToast('上传oss失败')
                    })
                });
            }
        });
    },



    // 同步处方
    // syncPrescription (e) {
    //     wx.showLoading({
    //         title: '加载中',
    //     })
    //     let id = e.currentTarget.dataset.id;
    //     let type = e.currentTarget.dataset.type;
    //     let jsonData ={
    // 		"orgid": "440004999", 
    // 		"actid": type === 'cancel'?'cxpressync':"dopressync",
    // 		"order_id" : id,
    // 		"rand": Math.random()
    //     }
    //     wx.request({
    //         url:  "https://zz.nxk520.com/nethosp/service/nethosp_interface.ashx",
    //         method: 'GET',
    //         data: jsonData,
    //         dataType: "json",
    //         complete: (res) => {
    //             wx.hideLoading();
    //             $service.showToast(res.data.msg);
    //         }
    //         });
    // },


    /** 结束问诊 */
    // 获取未开方原因下拉列表
    noPrescriptionList() {
        app.http.noPrescriptionList().then(res => {
            this.setData({
                noPrescriptionList: res.data.list
            })
        })
    },
    // 选择未开原因
    bindPickerChange(e) {
        console.log(e)
        let index = e.detail.value;
        this.setData({
            reasonsName: this.data.noPrescriptionList[index].reasonsName
        })
    },
    //修改问诊付费方式
    changePayMethod(e) {
        console.log(e);
        let {
            value
        } = e.detail
        console.log(value);
        let params = {
            logId: logId,
            paymentMethod: Number(value) + 1
        }
        app.http.updateInquiryPaidType(params).then((res) => {
            this.setData({
                paymentMethodNum: value
            })
            this.publicUtil_getInquiryLogDetails()
            // this.getDoctorStoreList()
        }).catch((err) => {
            console.log(err.msg);
        })
    },
    // 结束问诊
    async endInquiry(e) {
        if (!isEnd) return
        isEnd = false
        let index = e.target.dataset.index;
        try {
            // 自主开方结束
            if (this.data.isAuto == 1) {
              if  (index == 2 ) { // 未成功问诊
                wx.showModal({
                    content: '是否结束当前开方？',
                    success: (res) => {
                        if (res.confirm) {
                          this.autonomousPrescriptionEndInquiry(0)
                        }
                    }
                })
              } else if (index == 1) { // 成功问诊
                this.autonomousPrescriptionEndInquiry(1)
              }
            } else  {
               // 其他问诊借宿
                if (thenS_.prescriptionList.length == 0) {
                    let params = {
                        "inquiryPatientId": inquiryPatientId,
                        "unprescribedReasons": thenS_.reasonsName
                    }
                    await app.http.addNoPrescription(params)
                }
                app.webSocket.sendWebSocketMsg({
                    data: {
                        "logId": logId,
                        "packageType": 13
                    },
                    success: () => {
                        let endType = index == 1 ? 'endInquiry' : 'unSuccessfulInquiry'
                        app.http[endType]({
                            id: logId,
                            firstVisit: this.data.isFirstInquiry
                        }, true).then(res => {
                            $service.showToast('结束问诊成功');
                            setTimeout(function () {
                              wx.reLaunch({
                                  url: '/pages/doctor_side/index/index'
                              })
                          }, 1500);
                        }).catch(err => {
                            $service.showToast(err.msg);
                        })
                    },
                    fail: () => {
                        $service.showToast('操作失败')
                    }
                })
            }
        } catch (err) {
            $service.showToast('结束问诊失败')
        }
        setTimeout(() => {
            isEnd = true
        }, 3000)
    },
    // 监听网络变化 
    watchNetWork() {
        wx.onNetworkStatusChange((res) => {
            if (res.isConnected) {
                this.initWebSocket();
                if (this.data.log_type == 1) {
                    this.startRTC();
                }
            } else {
                isNetWork = false
                $service.showToast('网络连接异常')
            }
        })
    },
    getMessageheight() { //获取底部操作栏高度
        let query = wx.createSelectorQuery();
        query.select('.message').boundingClientRect(rect => {
            let clientHeight = rect.height;
            let clientWidth = rect.width;
            let ratio = 750 / clientWidth;
            let messageHeight = clientHeight * ratio + 64;
            this.setData({
                messageHeight
            })
        }).exec();
    },
    reserveInquiry() {
        wx.showModal({
            content: '是否保留此次问诊？',
            success(res) {
                if (res.confirm) {
                    app.webSocket.sendWebSocketMsg({
                        data: {
                            "doctorId": doctorId, //医生id
                            "logId": logId, //问诊id
                            "packageType": 32
                        },
                        success: (res) => {
                            $service.showToast('保留问诊成功')
                            setTimeout(() => {
                                wx.reLaunch({
                                    url: '/pages/doctor_side/index/index'
                                })
                            }, 1000)
                        },
                        fail: (err) => {
                            $service.showToast('操作失败');
                        }
                    })
                }
            }
        })
    },



    /* 
        廉江his接口    
    */
   hisDrugModal(e) {
      this.setData({
        hisModal: false
      })
   },
    // 获取药品用法用量
    getDictInfo(type) {
        app.http.getDictInfo({
          dictType: type
        }).then(res => {
            switch (type) {
              case 20: // 药品单位
                this.setData({
                  consumptionlist: res.data
                })
                break;
              case 40: // 包装单位
                
                break;
              case 51: // 西药用法
                this.setData({
                  list: res.data
                })
                break;
              case 52: // 中药服用方法，要求
                
                break;
              case 60: // 频率
                this.setData({
                  list2: res.data
                })
                break; 
              case 70: // 中药特殊煎法
                this.setData({
                  list: res.data
                })
                break;
              case 103: // 中药服用方法
                res.data.forEach(item => {
                  item.usageName = item.dictName
                })
                this.setData({
                  list2: res.data
                })
                break;             
              default:
                break;
            }
            console.log(res)
        }).catch(err => {
            $service.showToast(err.msg)
        })
    },
    // 获取廉江his就诊记录
    getClinicHistoryList() {
      let params = {
        "cardType": "03",
        "healthCardNo": this.data.inquiryMap.healthCardNo,
        "patientId": this.data.inquiryMap.patientId,
        "current": clinicPage,
        "size": 10,
        // "healthCardNo": '900663823',
        // "patientId": "DAF479145F2126E6E050A8C0010004EA",
      }
      if (lianjiangInquiryListEndDate && lianjiangInquiryListStartDate) {
        params.beginDate = lianjiangInquiryListStartDate
        params.endDate = lianjiangInquiryListEndDate
      }
      app.http.getClinicHistoryList(params).then(res => {
        if (res.data && res.data.count > this.data.wzlslist.length) {
          let list = [...this.data.wzlslist, ...res.data.clinicHistory]
          this.setData({
            wzlslist: list
          })
        } else {
          inqiuryLoading = false
        }
      }).catch(err => {
        $service.showToast(err.msg)
      })
    },
    // 获取廉江his药品列表
    getHisDrugInfoList(type, num) {
      let api = type == 1 ? 'getTraditionalDrugInfo' : 'getHisDrugInfoList'
        app.http[api]({
          "current": num,
          "drugName": thenS_.drug_name,
          "size": 20
        }).then(res => {
            var drugList = res.data.list
            drugList.forEach((item, index) => {
                item.drugSpecifications = item.packageSpec
                item.drugPrice = item.retailPrice
                item.storeName = '院内药店'
                item.drugId = item.drugCode
                item.id = item.drugCode
                item.storeId = 0
                if (type == 1) {
                  item.packageUnitName = item.retailUnitName
                  item.doseUnitIame = item.retailUnitName
                }
            })
            if (drugList) {
                for (var i = 0; i < drugList.length; i++) {
                    drugList[i].drug_usname = $service.nothingFun(drugList[i].drug_usname, '--')
                }
            }
            //判断选项卡情况
            if (thenS_.tapactive == 1) {
                if (page == 1) {
                    thenS_.loadingText = '';
                    thenS_.drugList = drugList;
                    thenS_.loadingType = true;
                } else {
                    if (!drugList || drugList.length == 0) {
                        thenS_.loadingType = false;
                        thenS_.loadingText = '没有更多了';
                    } else {
                        for (var i = 0; i < drugList.length; i++) {
                            thenS_.drugList.push(drugList[i]);
                            thenS_.loadingText = '加载更多';
                        }
                    }
                }
            } else {
                thenS_.loadingText = '';
                thenS_.drugList = drugList;
                thenS_.loadingType = true;
            }
            this.setData({
                drugList: thenS_.drugList,
                loadingText: thenS_.loadingText,
                loadingType: thenS_.loadingType,
            })
        }).catch(err => {
            console.log(err)
            $service.showToast(err.msg)
        })
    },
    liangjiangInqiuryToDetail(e) {
      this.getpageScrollTo()
      thenS_.openPageBox_up = thenS_.openPageBox;
      this.setData({
          clinicSeq: e.detail,
          openPageBox: 31,
          openPageBox_up: thenS_.openPageBox_up
      })
    },
    lianjiangHisChangeDate(e) {
      let {endDate, startDate} = e.detail
      if (endDate && startDate) {
        lianjiangInquiryListStartDate = startDate
        lianjiangInquiryListEndDate = endDate
        this.setData({
          wzlslist: [],
        })
        inqiuryLoading = true
        clinicPage = 1
        this.getClinicHistoryList()
      }
    },
    /* 
        *****    
    */

    // 处方详情
    toPreDetail(e) {
      let {id} = e.currentTarget.dataset
      $service.openPage(`/pages/user_side/index/index_health_guidance/index_health_guidance?type=4&id=${id}`)
    },
    // 自主开方
    // 修改就诊人信息
    doctorAddOrupdatePatientInfo(params) {
      params.paymentMethod = 1
      app.http.doctorAddOrupdatePatientInfo(params).then(res => {
        $service.showToast('操作成功')
        if (!logId) { 
          logId = res.data.logId
          inquiryPatientId = res.data.patientId
        }
        this.publicUtil_getInquiryLogDetails()
        this.closeBox('', 1)
      }).catch(err => {
        $service.showToast(err.msg)
      })
    },
    // 模糊搜索就诊人相关信息
    getSearchDoctorInquiryPatientInfoList() {
      let patientName = this.data.inquiryMap2.patientName
      let mobile =  this.data.inquiryMap2.patientPhone
      let patientIdcard =  this.data.inquiryMap2.patientIdcard
      app.http.getSearchDoctorInquiryPatientInfoList({
        patientName,
        mobile,
        patientIdcard
      }).then(res => {
        if (res.data.list.length != 0) {
          this.data.inquiryMap2 = res.data.list[0]
        }  else {
          // this.data.inquiryMap2 = {}
          // this.data.inquiryMap2.patientName = patientName
          // this.data.inquiryMap2.patientPhone = mobile
          // this.data.inquiryMap2.patientIdcard = patientIdcard
          this.getBirthdatByIdNo(patientIdcard)
        }
        this.setData({
          inquiryMap2: this.data.inquiryMap2
        })
      }).catch(err => {
        $service.showToast(err.msg)
      })
    },
    // 自主开方结束问诊
    autonomousPrescriptionEndInquiry(isSuccess) {
      app.http.autonomousPrescriptionEndInquiry({
        "autonomousAddress": this.data.inquiryMap.autonomousAddress,
        "addressCity": this.data.inquiryMap.addressCity,
        "deliveryMode": this.data.deliveryMode,
        "id": logId,
        "isSuccess": isSuccess,
        "patientName": this.data.inquiryMap.patientName,
        "payWay": this.data.payWay == 0 ? 'offline' : 'online',
        "phoneNumber": this.data.inquiryMap.patientPhone
      }).then(res => {
        if (isSuccess  == 0) { // 未成功问诊
          wx.redirectTo({
            url: '/pages/chat/doctor_chat/doctor_chat?isAuto=1',
          })
        } else { // 成功问诊
          if (this.data.payWay == 0) {
            wx.redirectTo({
              url: '/pages/chat/doctor_chat/doctor_chat?isAuto=1',
            })
          } else {
            this.getpageScrollTo()
            this.data.openPageBox = 29;
            this.setData({
                loginMiniQrcodeurl: res.data.loginMiniQrcodeurl,
                autoPreList: res.data.prescriptionList,
                openPageBox: this.data.openPageBox,
            })
          }
        }
      }).catch(err => {
        $service.showToast(err.msg)
      })
    },
    // 自主开方历史记录
    queryInquiryLogPrescriptionHistory() {
      app.http.queryInquiryLogPrescriptionHistory({
        searchKeywords: this.data.searchKeywords
      }).then(res => {
        this.setData({
          queryLogHis: res.data.list
        })
      }).catch(err => {
        $service.showToast(err.msg)
      })
    },
    autoHistoryInput(e) {
      this.setData({
        searchKeywords: e.detail.value
      })
    },
    // 自主开方选择支付方式
    changePay(e) {
      let {num, index} = e.currentTarget.dataset
      if (num == 1) {
        this.data.payWay = index 
      } else {
        this.data.deliveryMode = index
      }
      this.setData({
        payWay: this.data.payWay,
        deliveryMode: this.data.deliveryMode
      })
      console.log(num, index)
    },
    // 通过身份证获取用户出生日期
    getBirthdatByIdNo(idNo) {
      if (!$service.validateElement('idCard', idNo)) {return}
      let tmpStr = "";
      let sex = '';
      let age = ''
      if (idNo.length == 15) {
          sex = idCard.substring(14, 15) % 2
          tmpStr = idNo.substring(6, 12);
          tmpStr = "19" + tmpStr;
          age = new Date().getFullYear() - tmpStr.substring(0, 4)
          tmpStr = tmpStr.substring(0, 4) + "-" + tmpStr.substring(4, 6) + "-" + tmpStr.substring(6)
      }else if (idNo.length == 18){
          sex = idNo.substring(14, 17) % 2
          tmpStr = idNo.substring(6, 14);
          age = new Date().getFullYear() - tmpStr.substring(0, 4)
          tmpStr = tmpStr.substring(0, 4) + "-" + tmpStr.substring(4, 6) + "-" + tmpStr.substring(6)
      }
      this.data.inquiryMap2.patientBirthday = tmpStr
      this.data.inquiryMap2.patientSex = sex
      this.data.inquiryMap2.patientAge = age
      this.setData({
        inquiryMap2: this.data.inquiryMap2
      })
    },
    // 是否首诊
    chooseFirst(e) {
      this.setData({
        isFirstInquiry: Number(e.currentTarget.dataset.index) 
      })
    },
    // 自主开方选择城市区
    bindRegionChange(e) {
      let {value} = e.detail
      this.data.inquiryMap2.addressCity = value.join(' ') 
      this.setData({
        inquiryMap2: this.data.inquiryMap2
      })
    },
    inputEnjoin(e) {
      detailsEntrust = e.detail.value
    },
    editEnjoin() {
      app.http.updateDetailsEntrust({
        detailsEntrust: detailsEntrust,
        id: logId
      }).then(res => {
        $service.showToast('编辑成功')
        this.setData({
          openPageBox: 0
        })
      }).catch(err => {
        $service.showToast(err.msg)
      })
    }
})
